Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
COMP-202 Programming Basics COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others Chapter Outline • • Hardware & Software Programming Language • Syntax and Semantics • Identifiers • Formatting Rules • • • • Variables Types Assignment Expressions • Arithmetic Operators • Increment / Decrement Operators • Assignment Operators • • Type Conversions Development Life Cycle COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 2 What Do Other Sciences Do? • Life Science Example: • Study how a cell works • A Cell is something complex that already exists • Researcher tries to figure out how this complex cell works • Get background knowledge • Learn laboratory skills • Make hypothesis • Run many experiments to see whether hypothesis works • Engineer Example: • Build a bridge • Create something new • Must follow many rules --> must work • Must know the math, materials, physics, … COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 3 What Do Computer Scientists Do? • Example: • Build the web-portal for an online bookstore • Create something new • Webpages • Functionality: • Browse with keywords • Maintain your shopping cart • Perform checkout • What is more complex: a cell or a piece of software? COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 4 What Is Programming? • In order to understand what programming is, we need to know what a computer is: • A computer is a machine that executes lists of instructions • We feed a list of instructions to the computer and the computer executes them • The computer may apply the instructions on additional information fed to the computer (the input) • The computer may produce information as a result of executing this list of instructions (the output) COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 5 Recipe for Scrambled Eggs • Ingredients: two eggs, tablespoon of oil, salt • Instructions: • • • • Heat pan on stove until hot Add oil Crack eggs into pan Add salt A recipe is a series of steps What if we did not follow the order? • Optional: add milk / cheese • Mix until light and flakey • Output: scrambled eggs COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 6 Currency Exchange 1. Input (data that is needed to solve the problem): – Amount – Source Currency – Desired Currency 2. Instructions 1. Look up in table current exchange rate for the selected currencies 2. Calculate result as amount * exchange rate 3. Output (data that is produced by executing the instructions) – Result COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 7 What is a Program? • • • • • A program solves a particular task A program is a list of instructions The list must be ordered correctly A program has inputs and outputs Each instruction tells the computer to do something (an action, a calculation, a comparison) COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 8 What is Software? • Software = Program ? • Software typically consists of many subcomponents / modules / subprograms • Each subprogram solves a particular task • Software also includes the data to be used and manipulated • Input / output data • Internal data (e.g, table with exchange rates) COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 9 The Bank Machine: Functionality • • • • • • • • Withdraw money from checking account Show balance on checking account Show balance on saving account Transfer money from checking account to saving account Transfer money from saving account to checking account Deposit money on checking account Deposit money on saving account … COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 10 The Bank Machine: Interaction • Login (sub-program ) • Task menu (each being a sub-program) • Withdraw, Get balance, Deposit • Transfer • Bill payment • Once task is selected • Walk-through for specific task on hand • Requires different input data, produces different output • Allow many tasks in one session • Logout COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 11 The Bank Machine: Login • Input: pin • If pin is correct • Result: go to task menu • Else get new pin as input • If pin is correct • Result: go to task menu • Else get new pin as input • If pin is correct • Result: go to task menu • Else print warning, do not release card COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 12 The Bank Machine: Money Transfer • Input ? • Instructions? • Output? COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 13 Goal of this Course • Translate a complex task into the software that executes this task • Structure the problem space into many small sub-tasks • Write programs for each subtask • Connect the programs to build software • Often, output produced by one program is used as input for another program • At the end of the course, you will be able to write a program that simulates a bank machine, or implements a game, etc... COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 14 Programming = Writing Instructions • But to make things challenging: • Computers require very specific instructions, i.e., no details can be omitted • Computers are “stupid”, i.e, they follow instructions without knowing what they are doing • If you omit the proper instructions or include the wrong instructions, generally 4 things can happen when you run the program 1. You are really lucky and on that particular input your program works anyway. 2. The program gives incorrect output. 3. The program crashes. 4. The program goes on forever and ever. COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 15 Hardware and Software • Hardware • The physical, tangible parts of a computer • Keyboard, monitor, wires, chips, mouse • Software • Programs and data • A program is a series of instructions • A computer requires both hardware and software • Each is useless without the other COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 16 The Personal Computer - Input Devices CD / DVD Drive Hard Disk Plus Other (USB) Devices Camera Keyboard Microphone Mouse Plus Other (USB) Devices COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 17 The Personal Computer - Output Devices Monitor CD/DVD/Disk Speakers Plus Other (USB) Devices COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 18 CPU - Central Processing Unit • Performs Instructions • Arithmetic operations • Logic operations • Decisions • Controls (manipulates and moves) the information / data in a computer COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 19 Memory • Memory holds the data • Main memory (RAM): • Data has to be in main memory so that the CPU can access it • Volatile: lost when program exits / computer shuts off • Hard Disk / CD / DVD / Flash drive • Persistent • This is where you keep the data for long-term storage COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 20 Interaction Central Processing Unit Hard Disk Monitor Keyboard Main Memory COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others CD-RW 21 How Do We Store Things? • Computer memory is electronic. It's just a bunch of wires! • All it can recognize is “on” (current goes through) and “off” (no current goes through) • Using many of these on/off “switches” together, we can encode many things • For example, we can store whether it is morning or afternoon using the following encoding: • “If the 1st switch is on, then it must be PM. If the 1st switch is off, then it must be AM.” • By combining many (and yes, a computer has many!) switches, we can store more complex data COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 22 Encoding • How could you encode the day of the week? • If we just use 1 switch, there will not be enough information. • How many “switches” will we need? • How could you encode the letters of the alphabet? • How could you encode a 3 letter word? • How would you encode a sentence? COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 23 Storage is Exponential • In general, if there are n possible values to store, we can encode it using • log2(n) “switches” • Of course, there is no such thing as a fraction of a switch, so we will always have to round up. • Put another way, if we have n switches, we can store 2n values COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 24 Main Memory Each cell has a numeric address that uniquely identifies it 9278 9279 9280 9281 9282 9283 9284 9285 9286 .. . Main memory is divided into many memory locations (or cells) .. . COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others Each cell can contain a data value, e.g. 22, or the character ‘j’ 25 Bits and Bytes • Bit -- most basic unit of memory • 1 or 0, on or off • 1 Byte = 8 bits • In general, each byte of memory has a unique address • KB (210 bytes), MB (220 bytes), GB, TB, ... • In a computer, data values are stored as a sequence of bits 9278 9279 22 7 9278 9279 COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 00010110 00000111 26 Binary Encoding of Numbers • Humans use the decimal number system • Each digit (0, 1, ..., 9) in a number represents a power of 10 • 6 = 6 x 100 31 = 3 x 101 + 1 x 100 207 = 2 x 102 + 0 x 101 + 7 x 100 • Binary number system • Each number position (bit) represents a power of 2 • 6 = 1 x 22 + 1 x 21 + 0 x 20 = 110 31 = ? 207 = ? COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 27 Program Execution (1) • A program tells the CPU how to manipulate and/or move information • Programming is about processing information • Take some input, manipulate it in some way, and produce a particular output • Fetch-Execute Cycle • The CPU repeatedly performs the three following operations: • Reads the next instruction in the program • Figures out what the instruction means (add two values, load some value from memory, store some value in memory. compare two numbers • Performs the instruction COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 28 Program Execution (2) • Suppose you want to write a program that reads a number from the keyboard, adds 1 to it, and displays the new value to the screen • This program might consist of the following instructions: • READ a value from the keyboard and store it in memory location x • LOAD the value stored in memory location x into the CPU • ADD 1 to the value stored in the CPU • STORE the value currently in the CPU back into memory location x • DISPLAY the value stored in memory location x to the screen COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 29 Program / CPU / Memory • Example: • Input (read) a number from keyboard • Add 1 to it • Output it on screen Keyboard 17 Memory Monitor CPU 18 COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 30 Human and Computer Languages • Consider the following English sentence: "The lady hit the man with a baby." • Does this mean 1. A lady hit a man who had a baby? 2. A lady used a baby to hit a man? 3. A lady and a baby ganged up on a man and hit him. • Programming languages are designed in such a way that individual instructions (called statements) always have only one possible interpretation COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 31 Programming Languages • A programming language specifies the words and symbols that we can use to write a program • We know that a program is a series of instructions, and that these instructions are performed by the computer • We use this language to explain the instructions to the computer • A programming language employs a set of rules that dictate how the words and symbols can be put together to form valid program statements COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 32 Syntax and Semantics • • • • The syntax rules of a language define how we can put symbols and statements together to make a valid program The semantics of a program statement define what those symbols and statements mean (their purposes or roles in a program) A program that is syntactically correct is not necessarily logically (semantically) correct A program will always do what we tell it to do, not what we meant to tell it to do COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 33 Programming Language Levels • There are many programming language levels • machine language • assembly language • high-level language 0011001001001 add r1,5 $a0 $3f $64 $21 mov r1,r2 load ax,3 FORTRAN, Pascal, C, Ada, C++, Java • Each type of CPU (PowerPC processor, Intel processor, …) has its own specific machine language. These are the simple built-in instructions the CPU comes pre-designed with. • The other levels were created to make it easier for a human to write programs COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 34 Compilers • A program must be translated into machine language before it can be executed on a particular type of CPU • A compiler is a software tool which translates source code into a specific target language. Often, that target language is the machine language for a particular CPU type. • Input: files written in a high-level programming language • Output: executable binary file that can be processed by CPU • A different compiler is needed for each CPU type COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 35 Interpreter • An interpreter is another software tool which takes source code and translates it into a target language • However, the target language instructions it produces are executed immediately • No executable file is created COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 36 The Java Programming Language • Java was created by Sun Microsystems, Inc., now part of Oracle Corporation • It was introduced in 1995 and has become quite popular • It is an object-oriented language • It represents the program as a series of objects, each of which belongs to one of many categories called classes • The Java programming language combines both compilation and interpretation COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 37 Java Translation and Execution • The Java compiler translates Java source code into a special representation called bytecode • Java bytecode is not the machine language for any traditional CPU • Another software tool, an interpreter called the Java virtual machine, translates bytecode into machine language and executes it • Therefore the Java compiler is not tied to any particular machine • Java is considered to be architecture-neutral COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 38 Java Translation and Execution Java Source Code Java Bytecode .java file Java Virtual Machine .class file Java Compiler .class .class .class COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others .class .class 39 Java Program Structure • In the Java programming language: • • • • A program is made up of one or more classes A class contains one or more methods A method contains program statements Statements are the actual commands you issue • These terms will be explored in detail throughout the course • A Java program always contains a method called main() • This is where the program starts executing COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 40 Java Program Structure: Class // Comments about the class public class MyProgram { Class Header (Name of the Class) Class Body (where the fields and methods go) } Important note: the name of the file which contains this program MUST be the name of the class, followed by extension .java Here: MyProgram.java COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 41 Java Program Structure: Class // Comments about the class public class MyProgram { Method Header Name of Method // comments about the method public static void main(String [] args) { Method Body (where the statements go) } } COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 42 Formatting Rules • Spaces, blank lines, and tabs are collectively called white space • It is used to separate words and symbols in a program • Extra white spaces are completely ignored • A valid Java program can be formatted many different ways • Programs should be formatted for readability • Use proper indentation! • Use space and new lines! • Use comments! COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 43 AddTwoIntegers import java.util.Scanner; public class AddTwoIntegers { public static void main(String[] args) { int input1, input2, output; Scanner keyboard = new Scanner(System.in); // Read the numbers input1 = keyboard.nextInt(); input2 = keyboard.nextInt(); // Compute the result output = input1 + input2; // Display the result System.out.println(output); } } This is an example of a nicely formatted program COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 44 AddTwoIntegersBad import java.util.Scanner; public class AddTwoIntegersBad { public static void main(String[] args){ int input1, input2, output; Scanner keyboard = new Scanner(System.in); input1 = keyboard.nextInt();input2 = keyboard.nextInt(); output = input1 + input2;System.out.println(output); } } Do not do this! COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 45 What Application should I Use to Program? • Text Editor + Command line Compiler • Any text editor that saves plain text files can be used + • Emacs / RText / Alpha “understand” Java COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 46 Programming Using Text Ed + Cmd Line • Run text editor • Save new text as YourClassName.java • Give the program the same name as the class (.java) • Type in your program • Save the program • Store all your files in one directory for now • Open command line (MacOS: Terminal, Linux: Shell) • Compile the program (javac YourClassName.java) • The CPU does not understand the Java language! • Java Language is translated into language that the CPU understands • This produces a .class file • • Run the program (java NameOfClass) Observe the result and adjust the program if necessary COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 47 What Application should I Use to Program? • Integrated Development Environment (for Java) • DrJava • Very simple, targeted at beginners • http://www.drjava.org/ • Eclipse • Very powerful • http://www.eclipse.org/ • Many others exist: NetBeans, JCreator COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 48 Programming Using DrJava • Type in your program • Save the program • Store all your files in one directory for now • Give the program the same name as the class (.java) • Compile the program (hit Compile button) • The CPU does not understand the Java language! • Java Language is translated into language that the CPU understands • This produces a .class file • Run the program (hit Run button) • Observe the result and adjust the program if necessary COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 49 Identifiers • • • Identifiers are the words a programmer uses in a program They are used to give names to things Example of things that can be named with identifiers: • • • • • • • Classes Methods Variables Constants An identifier can be made up of letters, digits, the underscore character (_), and the dollar sign ($) Identifiers cannot begin with a digit Java is case sensitive, therefore Result and result are different identifiers COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 50 More on Identifiers • Sometimes we choose identifiers ourselves when writing a program (such as input1, AddTwoIntegers) • We should choose identifiers that are meaningful so that it is more readable for humans • Sometimes we are using another programmer's code, so we use the identifiers that they chose (such as println()) • Often we use special identifiers called reserved words that already have a predefined meaning in the language • A reserved word cannot be used in any other way • Examples of reserved words: class, public, static, void • There are many others COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 51 Identifier Exercise • Which of the following identifiers are invalid according to the Java rules for identifiers? Why are they invalid? myIdentifier _my_other_identifier yet-another-identifier $can 2for1 twoFor1 class my_class COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 52 Variables • A variable is a placeholder for values • We can store a value in a variable • We can use the value a variable contains to compute other values (which may be stored in other variables) or make decisions • Each variable has a name • The compiler allocates memory cells to hold the value of the variable, and assigns the name chosen for the variable to these cells • We can then refer to the value stored in these memory cells using the variable name • Much easier and more practical than using the addresses of the memory cells (and less error-prone) COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 53 Variable Declarations • Before we can store a value in a variable or use the value it contains, we have to declare it • A variable declaration is a statement that announces that we want to create and use a new variable • They can occur anywhere in a method, but they are typically at the beginning • They must indicate the name and the type of the new variable • Once a variable has been declared, we can store a value in it or use the value it contains • If you try to use a variable before it is declared, the compiler will generate an error COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 54 Syntax for Declaring Variables modifier type identifier = value ; (optional) (mandatory) (mandatory) (optional) (mand.) • Example modifiers: final, static, public, private, ... • Example types: int, float, char, ... • Identifier: as defined previously • Value: an expression matching the type (the expression is evaluated and its value is assigned to the variable) COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 55 More on Variable Declarations • Note that you can declare more than one variable with one variable declaration statement • The variable names are separated using commas • Example: int var1, var2, var3; COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 56 Variable Declaration Illustration int weightGain = 13; 9278 9279 9280 9281 9282 9283 9284 9285 9286 .. . 00000000 00000000 00000000 00001101 weightGain .. . COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 57 Types • A type is a category that a variable belongs to and determines: • How to interpret the value it contains • What are the possible values it can contain • All variables have a type • The type of a variable provides an answer to the following question: should the value of the variable be considered as an integer, a real number, a character, or maybe even something else? • For a computer, everything is stored as a series of ones and zeroes • We need a way to tell what the ones and zeroes represent and how they should be interpreted COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 58 Java Types • There are two broad kinds of types in Java • Primitive types • Reference types • We will see reference types later in the course • Primitive types represent very basic kinds of values • Primitive types are defined by the Java compiler COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 59 Primitive Types • There are exactly 8 primitive types in Java • Four of them represent integers (positive and negative whole numbers): • byte, short, int, long • Two of them represent floating point numbers (positive and negative numbers with decimal parts): • float, double • One of them represents characters: • char • And one of them represents boolean values (true or false): • boolean COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 60 Numeric Types • The difference between the various numeric primitive types is their size, and therefore the values they can store: Type Space Literal Minimum Maximum byte 8 bits 5 -128 127 short 16 bits 5 -32768 32768 int 32 bits 5 -2147483648 2147483647 long 64 bits 5 < -9 * 1018 > 9 * 1018 float 32 bits 5.2f +/- 3.4 * 1038 (with 7 significant digits) double 64 bits 5.2 +/- 1.7 * 10308 (with 15 signif. digits) COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 61 Real vs. Floating Point • Real number: number that can be given by an infinite decimal representation • 3.14159265... • However, we would need infinite memory to store a number with infinite decimal representation • Floating point number: • Approximation of a real number; can only hold a finite amount of decimal places • Needs only finite space (fits in a memory cell or a finite set of memory cells) COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 62 Characters • A char variable stores a single character from the Unicode character set char gender; gender = 'M'; • • • • A character set is an ordered list of characters, and each character corresponds to a unique number The Unicode character set uses 16 bits (2 bytes) per character, allowing for 65536 unique characters It is an international character set, containing symbols and characters from many world languages Character literals are delimited by single quotation marks: !'a'! 'X'! '7'! '$'! ','! '\n' COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 63 Boolean Values • • • A boolean expression is an expression that evaluates either to true or to false Named after George Boole, the inventor of Boolean algebra Similar concept in natural language • "The traffic light is red " • This expression is either true or false COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 64 Boolean Type • You can declare variables which are of type boolean • A boolean variable represents a true or false condition • A boolean can also be used to represent any two states, such as a light bulb being on or off • The literals true and false are the only valid values for a boolean type • Example: boolean done = false; // Some code here done = true; COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 65 The Assignment Statement • To store a value in a variable, we use the assignment statement • The assignment operator in Java is the = sign • The syntax for the assignment statement is the following: variable = expression; • The expression on the right of the = sign is evaluated • The result of evaluating the expression is stored in the variable on the left of the = sign • The left-hand side of the = must be a variable; it cannot be an expression • The = operator does not define an equation! COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 66 Reading From the Keyboard (1) To read values from the keyboard, we use the Scanner class • import java.util.Scanner; • First, we must declare a variable of type Scanner, and initialize it • • Scanner someName = new Scanner(System.in); • someName can be replaced by any identifier; keyboard is a good choice, but there is nothing special about it • Everything else, however, must be exactly as above • To read a value of type int from the keyboard, we use the following expression: someName.nextInt(); • someName must be replaced by the identifier you used when you declared the Scanner variable COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 67 Reading From the Keyboard (2) Thus, if you called your Scanner variable foo, you must write foo.nextInt() if you want to read an int value from the keyboard • The expression someName.nextInt() (where someName is a variable of type Scanner) can be used as the right side of an assignment statement: int input; input = someName.nextInt(); • The right side of the assignment statement is evaluated; this results in a value of type int being read from the keyboard • The value read from the keyboard is then stored in the variable on the left side of the assignment statement • • To read a value of type double instead of type int, replace nextInt() by nextDouble() COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 68 Displaying to the Monitor • Two built-in commands to print on the screen: • System.out.println(….stuff to print out….); • A line-break is printed after ….stuff to print out… • System.out.print(….stuff to print out….); • Only ….stuff to print out…. is printed COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 69 More on print / println • println() and print() each take one input (also called parameter or argument) • a character string: • println("Hello world!"); • the value of a variable: • println(output); • the combination of both: • println("The sum is " + output); • a combination can have more than two parts: • println("The sum is " + sum + " and the " + "difference is " + diff); COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 70 Examples of Displaying Text • System.out.println("Hello world!"); • The character string Hello world! is displayed • int value = 5; int result = 7 * value + 9; System.out.println(result); • The value 44 is displayed • double price = 44.99; System.out.println("This book costs " + price + " dollars"); • The character string This book costs 44.99 dollars is displayed COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 71 Countdown.java class Countdown { ! public static void main(String args[]) { ! ! System.out.print(“Three… ”); ! ! System.out.print(“Two… ”); ! ! System.out.print(“One… ”); ! ! System.out.print(“Zero… ”); ! ! System.out.println(“Liftoff!”); ! ! System.out.println (“Houston, we have a problem!”); ! } } What does this output? COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 72 Countdown Result • The following is displayed when the program Countdown is executed: Three… Two… One… Zero… Liftoff! Houston, we have a problem! Cursor ends up here! COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 73 Short Introduction to Classes • Java has many pre-defined classes • Example: Scanner • Look at: http://download.oracle.com/javase/6/docs/api/ • Java classes define methods that you as a programmer can call to execute their functionality • Examples • int num = s.nextInt(); • System.out.println(“Hey, got any grapes?”); • We will see later in the course how to write your own classes Use “.” operator to make method calls COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 74 The String Class • Java defines a class String with many methods • Example methods (there are many more): • • • • String toLowerCase() String toUpperCase() char charAt(int index) String substring(int beginIndex, int endIndex) • Reading a String from the keyboard • Scanner s = new Scanner(System.in); • String wordsOfWisdom = s.nextLine(); COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 75 Arithmetic Expressions • An expression is a combination of operators and operands • Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition Subtraction Multiplication Division Remainder Negation x x x x x + * / % -x y y y y y • An operand can be a literal value, a variable, or the value returned by a method call COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 76 Division with Integers • • • If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) The remainder operator (%) returns the remainder after dividing the second operand into the first Example: int numHours = 52; int fullDays = numHours / 24; int remainingHours = numHours % 24; • Division by 0 • Produces run-time error • Program has to avoid it, or it will crash COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 77 DivisonInt import java.util.Scanner; public class DivisionInt { public static void main(String[] args) { int numerator, denominator, output, remainder; Scanner keyboard = new Scanner(System.in); // Read the values System.out.println("Enter the numerator: "); numerator = keyboard.nextInt(); System.out.println("Enter the denominator: "); denominator = keyboard.nextInt(); output = numerator / denominator; remainder = numerator % denominator; System.out.println("The result is: " + output); System.out.println("The remainder is: " + remainder); } } COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 78 Operator Precedence • Operators can be combined into complex expressions result = total + count / max - offset; • Operators have a well-defined precedence which determines the order in which they are evaluated • Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation • Arithmetic operators with the same precedence are evaluated from left to right • Parentheses can always be used to force the evaluation order COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 79 Operator Precedence Exercises • What is the order of evaluation in the following expressions? a + b + c + d + e 1 2 3 a + b * c - d / e 4 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1 COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 80 Assignment Operator Precedence • The assignment operator has a lower precedence than the arithmetic operators answer = sum / 4 + MAX * lowest; 1 2 3 First the expression on the right hand side of the = operator is evaluated 4 Then the result is stored in the variable on the left hand side COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 81 TempConvert.java import java.util.Scanner; public class TempConvert { ! public static void main (String args[]) { ! int base = 32; ! double conversionFactor = 9.0 / 5.0; ! double fahrenheitTemp; ! int celsiusTemp; ! Scanner scan = new Scanner(System.in); ! celsiusTemp = scan.nextInt(); ! farenheitTemp = celsiusTemp * conversionFactor + base; ! ! ! System.out.println(“Celsius Temp = “ + celsiusTemp); System.out.println(“Farenheit Temp = “ + FarenheitTemp); } } COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 82 Assignment Operator Sides • The right and left hand sides of an assignment statement can contain the same variable count = count + 1; 1 First, 1 is added to the original value of count. The result is stored in a temporary memory location. 2 Then the result is stored back into count (overwriting the original value) The fact that the assignment operator has lower precedence than arithmetic operators makes this possible. COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 83 Constants • • • A constant is an identifier that is similar to a variable except that it holds one value for its entire existence The compiler will issue an error if you try to assign a value to a constant more than once in the program In Java, we use the final modifier to declare a constant final double PI = 3.14; • Constants have the following advantages: • They give names to otherwise unclear literal values • They facilitate changes to the code • More precision required? Change PI to 3.14159 in only one place • No need to search the whole program for occurrences of the value • They prevent inadvertent errors • Cannot type the wrong value by mistake COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 84 Circle.java import java.util.Scanner; public class Circle { public static void main(String[] args) { double radius, circumference, area; final double PI = 3.14; Scanner keyboard = new Scanner(System.in); // Read the radius System.out.println("Enter the radius: "); radius = keyboard.nextDouble(); // Perform calculations circumference = 2.0 * radius * PI; area = radius * radius * PI; System.out.println("The circumference is: " + circumference); System.out.println("The area is: " + area); } } COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 85 Boolean Expressions • Instead of evaluating to a numeric value, boolean expressions evaluate to either true or false myNumber > 0 // can be either true or false • You can assign the result of a boolean expression to a variable of type boolean: boolean positive; positive = (myNumber > 0); • Boolean expressions are often used to control the flow of execution of a program • We will see control flow in detail later in the course; we will cover boolean expressions in more detail then COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 86 Increment / Decrement Operators • The increment and decrement operators are arithmetic and operate on one operand • The increment operator (++) adds one to its operand • The decrement operator (--) subtracts one from its operand • The statement count++; is essentially equivalent to count = count + 1; • But there are some traps... COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 87 Increment / Decrement Forms • • • The increment and decrement operators can be applied in prefix form (before the variable) or postfix form (after the variable) When used alone in a statement, the prefix and postfix forms are basically equivalent; that is, when used alone in a statement, ++count; is equivalent to count++; which is equivalent to count = count + 1; However, they are not equivalent when they are used in expressions COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 88 Increment / Decrement Details • When used in a larger expression, the prefix and postfix forms have a different effect • In both cases the variable is incremented or decremented • But the value used in the larger expression depends on the form: Expression Operation Value Used in Larger Expression count++ add 1 add 1 subtract 1 subtract 1 old value of count new value of count old value of count new value of count ++count count---count COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 89 Increment / Decrement Details Example • If count currently contains 45, then total = count++; assigns 45 to total and 46 to count (count is incremented only after its value has been read and used in the expression) • If count currently contains 45, then total = ++count; assigns the value 46 to both total and count (count is incremented before its value is read and used in the expression) COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 90 Increment / Decrement Caveat • When using the postfix version of an increment or decrement operator, the value of the variable is incremented immediately after it has been read • Thus, if a variable is used more than once in an expression, its value may not be the same the second time it is used • Example: int count = 4; int total = 0; total = count++ + count++ + ++count; • After executing this code fragment, what is the value of total? COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 91 Increment / Decrement Advice • Using increment and decrement operators is fine if this operator is the only operation in a statement i++; // OK ++j; // OK as well • Avoid using increment and decrement operators in more complex statements total = count++ - --count; // Avoid! index = ++i * --j / k++; // Avoid too! COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 92 Assignment Operators (1) • Often we perform an operation using a variable, then store the result back into that variable • Java provides additional assignment operators to simplify that process • They combine the assignment operator with an arithmetic operator • total += 5; is equivalent to • total = total + 5; result = result * (count1 + count2); is equivalent to result *= count1 + count2; COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 93 Assignment Operators (2) • • In general, assignment operators have the form variable op= expression; which is equivalent to variable = variable op (expression); The entire expression on the right side of the assignment operator is evaluated • It can be a complex expression involving many levels of parentheses • Then, the result of evaluating that expression is used on the right hand side of the operator in the assignment operator • The left operand is the variable on the left of the assignment operator • The final result is stored back in the variable on the left-hand side of the assignment operator COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 94 Assignment Operators (3) • There are many assignment operators, including the following: Operator Example Equivalent To += x += y x = x + y -= x -= y x = x - y *= x *= y x = x * y /= x /= y x = x / y %= x %= y x = x % y COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 95 Data Conversion • Sometimes it is convenient to convert data from one type to another • For example, we may want to treat an integer as a floating point value during a computation • Conversions must be handled carefully to avoid losing information • There are two types of conversions: • Widening conversions • Narrowing conversions • But first, a word on precision COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 96 Precision • The precision of a type is the range of all possible values you can express with a variable of that type • Variables of type int have higher precision than variables of type short; you can express more values with a variable of type int than with a variable of type short • Variables of type double have higher precision that variables of type int; again, you can express more values with a variable of type double than with a variable of type int • There is a correlation between the number of bytes used to store a value of a given type, and the precision of that type • byte uses only 8 bits and has the lowest precision; double or long use 64 bits and have the highest precision COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 97 Conversion Types • Widening conversions occur when a value whose type has lower precision is converted to a type that has higher precision (such as a short to an int or an int to a double) • They are usually safe, as there is usually no information lost • Narrowing conversions occur when a value whose type has higher precision is converted to a type that has lower precision (such as an int to a short or double to int) • Information can be lost when conversions of this type occur COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 98 Assignment Conversion (1) • In Java, data conversions can occur in three ways: • Assignment conversion • Arithmetic promotion • Casting • Assignment conversion occurs when a value of one type is assigned to a variable of another type • Only widening conversions can occur via assignment (such as assigning a value of type int to a variable of type double) • If we attempt a narrowing conversion (such as assigning a value of type double to a variable of type int), the compiler will issue an error COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 99 Assignment Conversion (2) • Assignment conversions occur automatically • For example, if we attempt to assign the value of an expression of type int to a variable of type double, the value of the expression will be automatically converted to have type double • The second assignment statement below is legal: int i = 7;! double d = 3 + i; • The expression on the right-hand side has type int, which has lower precision than type double, the type of the variable on the left-hand side • The value of 3 + i gets converted to have type double and gets assigned to d COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 100 Assignment Conversion (3) • The second assignment statement below is illegal: double d = 7.0; int i = 3.0 + d; • The expression on the right-hand side has type double, which has higher precision than type int, the type of the variable on the left-hand side • The compiler will therefore report an error COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 101 Arithmetic Promotion • Arithmetic promotion happens automatically when operators in expressions convert their operands double kmPerLitre; int km = 1000; float litres = 85.0f; kmPerLitre = km / litres; km ➞ float 1 2 division result of type float 3 result ➞ double 4 assignment COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 102 Casting (1) • Casting (also called typecasting) is the most powerful, general, and dangerous, technique for conversion • It trusts that you know what you are doing • Both widening and narrowing conversions can be accomplished by explicitly casting a value • It is the only way to perform a narrowing conversion • To cast, the type you want to convert a value to is put in parentheses in front of the value being converted. The general syntax is thus: (desiredType) expression COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 103 Casting (2) • The cast does not change the type of the value in a variable for the rest of the program, only for the operation in which the value is cast • When casting from floating point to integer, the fractional part of the floating point is discarded double money = 25.80; ! int dollars; ! dollars = (int)money; • dollars contains the value 25, money still contains the value 25.8 COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 104 Casting (3) • Casting has higher precedence than the arithmetic operators int a = 3; Only the double b = 3.5; value of b is cast. a is not int c, d; cast. Result: 9 c = (int)b * a; d = (int)(b * a); The product of b and a is cast. Result: 10 COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 105 Conversion Traps (1) • Consider the following variable declarations: int total = 10; int count = 4; double result; • What will the value of result be after the following statement is executed? result = total / count; • The value of result is now 2.0 ! • The two operands of the division operator have type int; thus, integer division is performed, truncating the fractional part COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 106 Conversion Traps (2) • Casting one of the integer operands to double (or float) will result in floating point division being performed instead result = (float)total / count; • The value of result is now 2.5 • First, total is cast to type float • Arithmetic promotion occurs to promote count to have type float; floating point division is performed and the result of the division therefore has type float • The quotient is converted to type double before being assigned to result COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 107 Conversion Exercises • • • double x = 5.9; int y = (int) x; What is the value of y? int a = 5; float b = 7.3f; double c = 10.03; c = b + a;! What is the value of c? int a = 2, b = 5; double c = 22; c = a / b;! What is the value of c? 5 12.3 0.0 COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 108 Programming Errors • Compile-time errors: the compiler finds problems with syntax and other basic issues • If compile-time errors exist, an executable version of the program is not created • Logical errors: the program runs, but produces incorrect results output = input1 – input2; System.out.println("The sum is: " + output); • Run-time errors: a problem occurs during program execution, and causes the program to terminate abnormally (or crash) • Division by 0 COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 109 Development Life Cycle Debugging • Write Code Compile Syntax Err? • errors Testing 0 errors Run Program Yes Log./Run Err? No No Enough Testing? Yes Errors might take a long time to debug Important Note: When you compile for the first time and see 150 errors, do not despair. Only the first 1 or 2 errors are relevant. Fix those and compile again. There should be fewer errors (like 50). Repeat until no errors. COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 110 Problem Solving • The purpose of writing a program is to solve a problem (or rather, have the computer solve a problem for us) • The general steps in problem solving are: • • • • • • • Understand the problem Dissect the problem into manageable pieces Design a solution for each of the pieces Consider alternatives to the solutions and refine them Implement the solutions Test the solutions and fix any problems that exist Combine the solutions for each of the piece to obtain the solution to the original problem COMP-202 - Programming Basics, © 2013 Jörg Kienzle and others 111