450 likes | 572 Views
Introduction. COMP 401, Spring 2013 Lecture 1 1/10/2013. How do we understand the world?. The Evolution of Programming. Simple programs are programmed simply. A program can just be a sequence of instructions. Each instruction causes a change in overall state.
E N D
Introduction COMP 401, Spring 2013 Lecture 1 1/10/2013
The Evolution of Programming • Simple programs are programmed simply. • A program can just be a sequence of instructions. • Each instruction causes a change in overall state. • May employ simple loops and conditional execution (i.e., if/then statements).
The Evolution of Programming • As a program becomes more complex… • Refactor common sequences of operations into parameterized functions or procedures. • Can be generalized and put into libraries that can be used across different programs.
The Evolution of Programming • As complexity continues to grow… • Developing a program as recipe-like sequence of instructions becomes increasingly difficult. • Need to be able to develop and understand our programming more like the way we understand the world. • As a set of interacting abstractions. • With different parts of the program operating at different levels of abstraction. • This is object-oriented programming.
Object-Oriented Programming • Programs expressed as a set of software “objects”. • Each object is associated with a set of data and a set of functions/procedures that operate with that data. • Objects are defined by their “class”. • Each class represents an abstraction. • Abstractions often layered on top of each other and/or composited into more complex abstractions. • Key challenge is developing the appropriate abstractions. • The operation of the program is the result of creating objects and having them interact with each other.
Major Themes Of This Course • Abstraction • Encapsulation • Inheritance • Polymorphism • Delegation • Design Patterns • Asynchronous Programming
Course Info • Sakai • Turning in assignments and as a gradebook • Piazza • Course notes, resources, Q&A, and all of other course related communication. • Should have received an invitation email either last night or this morning. • If not, come see me after class. • http://piazza.com/unc/spring2013/comp401/home
Syllabus Review • Who I am • Who the TAs are • Office hours TBA • Textbook / Resources • No required text. • Will be posting links to lots of on-line materials on Piazza course resources page.
Prerequisites • This should not be your first introduction to programming. • COMP 110 or 116 • High school • Hobbyist / Profession experience • If you have never programmed in Java before • http://www.oracle.com/technetwork/java/compile-136656.html • http://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.html • Many others. • Your goal should be to get up to speed on basic syntax and control structures. • We’ll be reviewing some of these today.
Assignments and Exams • 8 programming assignments • 2 midterms • Friday, 2/8 • Friday 3/22 • 1 final exam • Saturday, 5/4, 12:00 noon • Location TBA
Grading • 40% assignments • 10% recitations • 15% x 2 midterms • 20% final • Computing your grade • Each component mapped to a 4.0 scale • 4.0 = A, 3.0 = B, 2.0 = C, 1.0 = D • Assignments and recitations will be mapped as follows: • 95% -> 4.0 • 90% -> 3.5 • 80% -> 2.5 • 70% -> 1.5 • 40% -> 0.0 • Exams will be curved
Assignments • May restrict the use of certain Java libraries and/or features. • May require the use of certain programming techniques or approaches to the solution. • Correctness is but one criteria for grading. • Elegance and readability will also count. • Some of the assignments will build on top of each other. • This can make things difficult if you don’t get an assignment working. • You should keep working on an assignment until you do get it working. • You will get credit for the assignment due next. • If you catch up, you will get up to 50% credit for assignments that were originally late.
Honor Code • Can discuss assignment solutions at a high level but not at the level of code. • Code sharing = cheating • You are allowed to pattern your code after anything I post (i.e., class examples, etc.). • Can help each other debug, but again up to the point of sharing or writing code for another person. • If it feel wrong, it is wrong. • If you’re not sure, ask.
Recitations • Recitations are mandatory. • Attendance will be taken. • If you have a valid excuse, you must notify me in advance. • If missed for unforeseen circumstances (sickness, etc.), please be prepared to provide documentation. • There will be graded quizzes/exercises during recitations. • You are free to go to any of the 4 recitations, but try to go to the one you are registered for. • The midterms will be held in recitation. • For these, you must go to the recitation you are registered for. • Tomorrow’s recitation is cancelled.
Adding The Course • If you are not already registered, we will be trying to accommodate everyone. • Assumption is that some of you will drop. • But if not, we’ll be tight. • Send email to Jodie Turnbull • turnbull@cs.unc.edu • Subject: Adding COMP 401 • Include PID and choice of recitation • Please cc me as well.
OO Programming Languages • Almost all modern programming languages support some sort of object-oriented programming. • Not all of them will do so in the same way. • There isn’t just one way of being object-oriented. • We’ll be using Java • Some things will be conceptual and will apply broadly to many other OO programming languages. • Some things will be specific to the object-oriented mechanisms provided by Java
Installing the Java SDK • Java SE • Latest version is 7 update 10 • Sometimes referred to as 1.7 • You want the SDK (not just the JRE) • Available from Oracle at: • http://www.oracle.com/technetwork/java/javase/ • Mac Users • Built in version of Java is 1.6 • Strange relationship between Apple and Oracle. • This should work for what we are going to do. • Latest version is available from Oracle • But, only for latest operating system (i.e., Mountain Lion) running on a 64-bit processor
Eclipse • Java-based Integrated development environment (IDE) • Not necessarily the best, but reasonable, free, and fairly straightforward to use. • Available at http://eclipse.org • You don’t have to use it for assignments, but… • Some recitation exercises will require it so you need to have it installed. • I will be using it for examples in class.
Program Organization and Execution • All code in Java is organized into classes and interfaces • One public class or interface per file. • Not strictly true, but accept this as true for now. • Also, don’t worry about what an interface is for now. • Must match file name. • Classes can be organized into “packages”. • Again, more on that later. • Java compiler (javac) produces “byte code”. • Java interpreter (java) executes program • Need to specify a specific class name as the “main class”. • Interpreter starts execution with the method “main” • Must be defined with the signature: public static void main(String[] args)
Hello, World (1/2) • Open a plain text editor. • Create a file called HelloWorld.java • Enter the following text: public class HelloWorld { public static void main (String[] args) { System.out.println(“Hello, World!”); System.out.println(“This program was passed “ + args.length + “ arguments:”); for (inti=0; i<args.length; i++) { System.out.println(“Arg “ + i + “: “ + args[i]); } } }
Hello, World (2/2) • At a terminal command line (console for you Windows people), execute the following commands: > javacHelloWorld.java > Java HelloWorld Note that the “>” represents the command prompt.
Hello, World Notables • Demonstrates: • Use of javac and java from the command line • Appropriate declaration of main • Using a for loop to iterate over an array • Using System.out.println for console output • See reference documentation for System class • Link on Piazza resources page • Automatic type conversion from integer to string • + operator for string concatenation
Hello, World – take 2 • Same as before, but with Eclipse. • Eclipse Workspace • Creating new project • Creating a new package • Creating new class • Setting up runtime arguments in a “Run Configuration” • More in recitation next week
Fundamental Characteristics of Java • Strongly typed • Variables must be declared with a type specified. • Dichotomy between value types and reference types. • In some OO languages, everything is an object. • Not quite true in Java. • Some basic data types are objects (e.g., String, arrays) • Other basic data types are not (integers, real numbers, booleans) • Garbage collected memory • Memory is automatically allocated when objects are created. • Memory is automatically reclaimed when no possible reference to an object can exist.
A Word About Types Value Types Reference Types String Array Objects typed by their class Classes themselves • Integers • Real numbers • Booleans • Character • Values types are defined entirely by their value. • Reference types are structures in memory. • Address in memory uniquely identifies them. • The “value” of a variable that holds a reference type is this address. • Associated with “methods” and “fields” • Fields are also known as “members”
Value Types • Integers • byte, short, int, long • Difference is in size (1, 2, 4, or 8 bytes) • No “unsigned” version • Decimal (255), hexidecimal (0xff), and binary (0b11111111) literal formats • Real Numbers • float, double • Difference is in precision. • Characters • char • Characters in Java are 16-bit Unicode values • Literals use single-quote: ‘c’ • Non-printable escape sequence: ‘\u####’ where # is hex digit. • Example: ‘\u00F1’ for ñ • Logical • boolean • Literals are true and false
Reference Types • String • Array • Objects defined by programmer • Defined by its “class” • Classes themselves are objects • null • Valid literal value for all reference types • Basically indicates that there is no value. • The “.” operator “dereferences” a reference type in order to access associated methods and fields.
Strings • a = “A String ”; • a.length(); • 9 • a.charAt(3); • ‘t’ • a.concat(“am I”); • “A String am I” • a + “am I”; • Same as above • a.equals(“B string”); • false • a.substring(2,5); • “Stri” • a.trim(); • “A String” • String class • Sequence of chars • Some common methods: • length() • charAt(intidx) • concat(StringotherString) • Can also use “+” • equals(Objectobj) • Be careful about using “==” • substring(int start, int end) • trim() • Strings are immutable • Operations that change/alter a string are really giving you a new one.
Arrays • Container for a fixed number of values with the same type. • Zero based indexing. • Variables for arrays declared by using [] after type. • Type of the variable is Array • Type of each entry is specified by type name before [] • Empty arrays can be created with new keyword. • Size must be provided. • What do I mean by “empty”? • Literal array syntax can be used to create array from literal values (or expressions). int[] iarray; Declared, but not created. iarray = new int[10]; Now it’s created, but uninitialized. len = iarray.length; Length available as public field. Note, not a method. iarray[0] = 3; 0th item set iarray[-1]; Illegal index iarray[10]; Index out of bounds int[] iarray = {1,2,(2+1)}; Declared and items initialized all in one.
Variables • Variable names should start with a letter and can contain letters, digits, $, or _ • Can not start with digit • Should not use $ (just don’t) • Should not start with _ • Case sensitive • Can not be a keyword • Legal: • foo, bar, a_variable, var123 • Legal but not considered good: • var_with_$, _badness • Illegal: • 1var, while, break, this has whitespace
Expressions • A sequence of symbols that can be evaluated to produce avalue. • Can be used wherever a value is expected. • Types of expressions: • Literal values: 123 • Variable names: a_variable • Public class/object fields: Math.PI • Value as a result of a function call: foo() • Expressions combined by operators: 4+3*2
Operators • Unary: +, -, !, ++, -- • Arithmetic: +, -, /, *, % • Relational: ==, !=, >, >=, <, <= • Boolean: &&, || • Ternary: ?: • expression ? if_true : if_false • Bitwise: ~, <<, >>, >>>, &, |, ^ • Be aware of precedence • Can be controlled by explicitly grouping with ()
I Spy... double height = 1.77; • ... a type • ... a variable • ... a boolean literal • ... an integer literal • ... a real literal • ... a string literal • ... a named constant • ... an assignment • ... an expression • ... a cast • ... a method call booleanoverWeight = false; final intHIGH_BMI = 27; Stringname =“joe”; char firstChar= name.charAt(0); intbmi= (int) weight/(height * height); intweight = “seventy”;
Statements and Blocks • Statements end in ; • A complete unit of execution. • Types of statements: • Variable declaration • Expression statement • Not really useful unless the expression has a side effect. • Assignment • Conditional • Loop • Method call • Blocks • Zero or more statements enclosed in curly braces { } • Allowed anywhere a single statement is allowed.
Conditional Execution: if-else if-else if (expression) { block } else if (expression) { block } else { block }
if example if (score > 90) { System.out.println(“You got an A!”); } else if (score > 80) { System.out.println(“You got a B.”); } else if (score > 70) { System.out.println(“You got a C?”); } else if (score > 60) { System.out.println(“You got a D :-(“); } else { System.out.println(“You failed”); }
Conditional Execution: switch • Works with basic value data types • Works with strings as of Java 7 • Execution starts at first matching case value (or default if given). • Continues until break statement or end of switch. switch (expression) { case value: statements break; case value: statements break; ... default: statements }
Switch Example switch (c) { case 'a': case 'e': case 'i': case 'o': case 'u': System.out.println("Vowel"); break; default: System.out.println("Consonant"); }
Loops: while while (expression) { block } do { block } while (expression);
while example int sum = 0; intn = 1; while (n < 11) { sum += n; n++; } System.out.println(“The sum of 1 to 10 is: “ + sum);
Loops: for for (init; test; update) { block }
for example int sum = 0; for(intn=1; n<11; n++) { sum += n; } System.out.println(“The sum of 1 to 10 is: “ + sum); • Note that variable n is declared as part of init expression in for loop. • This is a common programming idiom if loop variable is only needed for the loop.
Method Calls • The terms “method”, “function”, and “procedure” get used almost interchangeably. • There are technical distinctions • Every method in Java is either a “class” method or an “instance” method. • Class methods are declared with the keyword “static” • Calling a class method: • ClassName.methodName(parameters) • Calling an instance method: • objectReference.methodName(parameters) • Within the body of a class method or instance method, we can omit the class name or object reference if we are trying to call another class or instance method associated with the same class or instance. • methodName(parameters) • Parameters are a comma separated list of values (or expressions) • Must match in number and type according to method’s signature.
Why CS? • Develops critical thinking and creative problem solving skills • Trains you to think systematically. • Information is fundamental • The electronics are simply expedient. • You want to make a difference in the world. • Any advance in any endeavor is going to involve computing.