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
Week 1: Java Bootcamp Dr. Jeff Gray [email protected] http://gray.cs.ua.edu July 22, 2013 9:00am-3:30pm These slides available at: http://www.cs.ua.edu/~gray/outreach/camps/week1/ Camp Introduction • Liability forms • Photos throughout the week • Lunch each day – 11:00am-12:00pm Today: Steak day at the Freshens Food Court Tomorrow: Pizza lunch (Student Services center) Tue-Thu: Lunch in the Freshens Food Court (Ferguson Center) Fri: Catered lunch • Restrooms • USB Stick • Assumption – general computer knowledge Using Windows Explorer to: • Copy files • Create new folders/directories • Navigate directories Special Events • Tuesday night from 6:15pm-8:15pm Social event – swimming at Outdoor Rec Pool Mandatory for all dormers to attend Commuters also welcome • Wednesday afternoon Special snack! • Thursday robotics lab visit Dr. Monica Anderson • Thursday night Possible social event – wiffle ball on the quad • Friday talk by Mrs. Dill Camp rules • Camp Rules No cell phone usage in class except for emergencies No headphones (except for project need) No surfing the web or playing games during lectures No food or drink are allowed in the lab Pay attention during class exercises; do not jump ahead and let us know if you fall behind Because of the large size of the camp, please keep discussions to a minimum to assist others in hearing instructions Quite in the hallways – classes in session Disclaimer • This is a “bootcamp” – it is designed to provide very quick immersion into a specific computer language; based on several methods for teaching Java since 1998 • We try to cover 16-weeks worth of material in 1 week • Obviously, we will not go into depth in many topics and this week primarily serves as an overview of Java • You will have a general view of Java at the end of the week, but not at a proficient level of expectation to take the AP computer science course • This is really a “teaser” to introduce you to computer science and prepare you with enough skills to be successful in the future camp weeks • We make not claim that you will be a Java expert at the end of the week, but hopefully you will learn some new things Free Java Resources • We do not provide you with a textbook for the camp, but there are several free resources available on the internet • Please do not print these on our printers (30 students times hundreds of pages = lots of dead trees!), but rather view online • http://www.mindview.net/Books/TIJ/ • http://mcis.western.edu/freejavabook/ • http://math.hws.edu/javanotes/ • http://www.bluepelicanjava.com/ Motivation for Studying CS • See http://gray.cs.ua.edu/outreach/why-cs-talk/why-cs-talk.ppt Let’s Get Started!!!!!! Analog vs. Digital • There are two basic ways to store and manage data: • Analog continuous, in direct proportion to the data represented music on a record album - a needle rides on ridges in the grooves that are directly proportional to the voltages sent to the speaker • Digital the information is broken down into pieces, and each piece is represented separately music on a compact disc - the disc stores numbers representing specific voltage levels sampled at specific times Digital Information • Computers store all information digitally: numbers text graphics and images video audio program instructions • In some way, all information is digitized - broken down into pieces and represented as numbers Representing Text Digitally • For example, every character is stored as a number, including spaces, digits, and punctuation • Corresponding upper and lower case letters are separate characters Hi, Heather. 72 105 44 32 72 101 97 116 104 101 114 46 Binary Numbers • Once information is digitized, it is represented and stored in memory using the binary number system • A single binary digit (0 or 1) is called a bit • Devices that store and move information are cheaper and more reliable if they have to represent only two states • A single bit can represent two possible states, like a light bulb that is either on (1) or off (0) • Permutations of bits are used to store values Bit Permutations 1 bit 0 1 2 bits 00 01 10 11 3 bits 000 001 010 011 100 101 110 111 4 bits 0000 1000 0001 1001 0010 1010 0011 1011 0100 1100 0101 1101 0110 1110 0111 1111 Each additional bit doubles the number of possible permutations Bit Permutations • Each permutation can represent a particular item • There are 2N permutations of N bits • Therefore, N bits are needed to represent 2N unique items 1 bit ? 21 = 2 items How many items can be represented by 2 2 bits ? 2 = 4 items 3 bits ? 23 = 8 items 4 bits ? 24 = 16 items 5 bits ? 25 = 32 items Converting Binary to Decimal • Consider what the decimal number “1,234” means: 1234 = 1000 + 200 + 30 + 4 = 1*1000 + 2*100 + 3*10 + 4 * 1 = 1*103 + 2*102 + 3*101 + 4*100 • In general, na…n1n0 represented in base “b” is: na…n1n0 = na*ba + … + n1*b1 + n0*b0 • Apply this to generalization to binary “01101100” (b=2) 01101100 = 0*27 + 1*26 + 1*25 + 0*24 + 1*23 + 1*22 + 0*21 + 0*20 = 0*128 + 1*64 + 1*32 + 0*16 + 1*8 + 1*4 + 0*2 + 0*1 =0 + 64 + 32 + 0 +8 +4 +0 +0 = 64 + 32 + 8 + 4 = 108 Memory 9278 9279 9280 9281 9282 9283 9284 9285 9286 Main memory is divided into many memory locations (or cells) Each memory cell has a numeric address, which uniquely identifies it Storing Information 9278 9279 9280 9281 9282 9283 9284 9285 9286 10011010 Each memory cell stores a set number of bits (usually 8 bits, or one byte) Large values are stored in consecutive memory locations Storage Capacity • Every memory device has a storage capacity, indicating the number of bytes it can hold • Capacities are expressed in various units: Unit Symbol Number of Bytes kilobyte KB 210 = 1024 megabyte MB 220 (over 1 million) gigabyte GB 230 (over 1 billion) terabyte TB 240 (over 1 trillion) Java • A programming language specifies the words and symbols that we can use to write a program • A programming language employs a set of rules that dictate how the words and symbols can be put together to form valid program statements • The Java programming language was created by Sun Microsystems, Inc. • It was introduced in 1995 and it's popularity has grown quickly since 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 Similar to how a book is broken into chapters, paragraphs, sentences, and words. This serves as an organizational structuring mechanism. • These terms will be explored in detail throughout the week • A Java application always contains a method called main Java Program Structure // comments about the class public class MyProgram { class header class body Comments can be placed almost anywhere } Java Program Structure // comments about the class public class MyProgram { // comments about the method public static void main (String[] args) { method body } } method header Identifiers • Identifiers are the words a programmer uses in a program • 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 - Total, total, and TOTAL are different identifiers • By convention, programmers use different case styles for different types of identifiers, such as title case for class names - Lincoln upper case for constants - MAXIMUM Identifiers • Sometimes we choose identifiers ourselves when writing a program (such as Lincoln) • Sometimes we are using another programmer's code, so we use the identifiers that he or she chose (such as println) • Often we use special identifiers called reserved words that already have a predefined meaning in the language; a reserved represents the core of the Java language • A reserved word cannot be used in any other way Reserved Words • The Java reserved words: abstract assert boolean break byte case catch char class const continue default do double else enum extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while White Space • Spaces, blank lines, and tabs are called white space • White space is used to separate words and symbols in a program • Extra white space is ignored • A valid Java program can be formatted many ways • Programs should be formatted to enhance readability, using consistent indentation Program Development • The mechanics of developing a program include several activities writing the program in a specific programming language (such as Java) translating the program into a form that the computer can execute investigating and fixing various types of errors that can occur • Software tools can be used to help with all parts of this process • Integrated Development Environments (IDEs) like Eclipse combine all of these activites (Tuesday) Language Levels • There are four programming language levels: machine language assembly language high-level language fourth-generation language • Each type of CPU has its own specific machine language • The other levels were created to make it easier for a human to read and write programs Programming Languages • Each type of CPU executes only a particular machine language • A program must be translated into machine language before it can be executed • 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 • The Java approach is somewhat different Java Translation • 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, called an interpreter, 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 Java Translation Java source code Java compiler Java bytecode Bytecode interpreter Bytecode compiler Machine code Development Environments • There are many programs that support the development of Java software, including: Sun Java Development Kit (JDK) Sun NetBeans IBM Eclipse Borland JBuilder MetroWerks CodeWarrior BlueJ jGRASP • Though the details of these environments differ, the basic compilation and execution process is essentially the same Syntax and Semantics • The syntax rules of a language define how we can put together symbols, reserved words, and identifiers to make a valid program • The semantics of a program statement define what that statement means (its purpose or role 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 Errors • A program can have three types of errors • The compiler will find syntax errors and other basic problems (compile-time errors) If compile-time errors exist, an executable version of the program is not created • A problem can occur during program execution, such as trying to divide by zero, which causes a program to terminate abnormally (run-time errors) • A program may run, but produce incorrect results, perhaps using an incorrect formula (logical errors) Basic Program Development Edit and save program errors errors Compile program Execute program and evaluate results Applets • A Java application is a stand-alone program with a main method (like the ones we've seen so far) • A Java applet is a program that is intended to be transported over the Web and executed using a web browser • An applet also can be executed using the appletviewer tool of the Java Software Development Kit • An applet doesn't have a main method • Instead, there are several special methods that serve specific purposes • We will only concentrate on applications this week Variables • A variable is a name for a location in memory • A variable must be declared by specifying the variable's name and the type of information that it will hold data type variable name int total; int count, temp, result; Multiple variables can be created in one declaration Variable Initialization • A variable can be given an initial value in the declaration int sum = 0; int base = 32, max = 149; • When a variable is referenced in a program, its current value is used Assignment • An assignment statement changes the value of a variable • The assignment operator is the = sign total = 55; • The expression on the right is evaluated and the result is stored in the variable on the left • The value that was in total is overwritten • This is not a mathematical EQUATION • You can only assign a value to a variable that is consistent with the variable's declared type Constants • A constant is an identifier that is similar to a variable except that it holds the same value during its entire existence • As the name implies, it is constant, not variable • The compiler will issue an error if you try to change the value of a constant • In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69; Constants • Constants are useful for three important reasons • First, they give meaning to otherwise unclear literal values For example, MAX_LOAD means more than the literal 250 • Second, they facilitate program maintenance If a constant is used in multiple places, its value need only be updated in one place • Third, they formally establish that a value should not change, avoiding inadvertent errors by other programmers Primitive Data • There are eight primitive data types in Java • Four of them represent integers: byte, short, int, long • Two of them represent floating point numbers: float, double • One of them represents characters: char • And one of them represents boolean values: Boolean Question: What does Boolean refer to? • Question: Why would we need so many different types? Numeric Primitive Data • The difference between the various numeric primitive types is their size, and therefore the values they can store: Type Storage Min Value Max Value byte short int long 8 bits 16 bits 32 bits 64 bits -128 -32,768 -2,147,483,648 < -9 x 1018 127 32,767 2,147,483,647 > 9 x 1018 float double 32 bits 64 bits +/- 3.4 x 1038 with 7 significant digits +/- 1.7 x 10308 with 15 significant digits Characters • A char variable stores a single character • Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n' • Example declarations: char topGrade = 'A'; char terminator = ';', separator = ' '; • Note the distinction between a primitive character variable, which holds only one character, and a String object, which can hold multiple characters Character Sets • A character set is an ordered list of characters, with each character corresponding to a unique number • A char variable in Java can store any character from the Unicode character set • The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters • It is an international character set, containing symbols and characters from many world languages • See http://www.unicode.org/charts/ Characters • The ASCII character set is older and smaller than Unicode, but is still quite popular • The ASCII characters are a subset of the Unicode character set, including: uppercase letters A, B, C, … lowercase letters a, b, c, … punctuation period, semi-colon, … digits 0, 1, 2, … special symbols &, |, \, … control characters carriage return, tab, ... • See http://www.lookuptables.com/ Boolean • A boolean value represents a true or false condition • The reserved words true and false are the only valid values for a boolean type boolean done = false; • A boolean variable can also be used to represent any two states, such as a light bulb being on or off Expressions • An expression is a combination of one or more operators and operands • Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition Subtraction Multiplication Division Remainder + * / % • If either or both operands used by an arithmetic operator are floating point, then the result is a floating point Division and Remainder • If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 / 3 equals 4 8 / 12 equals 0 • The remainder operator (%) returns the remainder after dividing the second operand into the first 14 % 3 equals 2 8 % 12 equals 8 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, but parentheses can be used to force the evaluation order Operator Precedence • What is the order of evaluation in the following expressions? a + b + c + d + e 1 2 3 4 a + b * c - d / e 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1 Expression Trees • The evaluation of a particular expression can be shown using an expression tree • The operators lower in the tree have higher precedence for that expression + a + (b – c) / d / a b d c Assignment Revisited • The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer = 4 sum / 4 + MAX * lowest; 1 3 Then the result is stored in the variable on the left hand side 2 Assignment Revisited • The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count count = count + 1; Then the result is stored back into count (overwriting the original value) Increment and Decrement • The increment and decrement operators use only one operand • The increment operator (++) adds one to its operand • The decrement operator (--) subtracts one from its operand • The statement count++; is functionally equivalent to count = count + 1; Increment and Decrement • The increment and decrement operators can be applied in postfix form: count++ • or prefix form: ++count • When used as part of a larger expression, the two forms can have different effects • Because of their subtleties, the increment and decrement operators should be used with care Assignment Operators • Often we perform an operation on a variable, and then store the result back into that variable • Java provides assignment operators to simplify that process • For example, the statement num += count; is equivalent to num = num + count; Assignment Operators • There are many assignment operators in Java, including the following: Operator += -= *= /= %= Example x x x x x += -= *= /= %= y y y y y Equivalent To x x x x x = = = = = x x x x x + * / % y y y y y Assignment Operators • The right-hand side of an assignment operator can be a complex expression • The entire right-hand expression is evaluated first, then the result is combined with the original variable • Therefore result /= (total-MIN) % num; is equivalent to result = result / ((total-MIN) % num); Assignment Operators • The behavior of some assignment operators depends on the types of the operands • If the operands to the += operator are strings, the assignment operator performs string concatenation • The behavior of an assignment operator (+=) is always consistent with the behavior of the corresponding operator (+) Interactive Programs • Programs generally need input on which to operate • The Scanner class provides convenient methods for reading input values of various types • A Scanner object can be set up to read input from various sources, including the user typing values on the keyboard • Keyboard input is represented by the System.in object Reading Input • The following line creates a Scanner object that reads from the keyboard: Scanner scan = new Scanner (System.in); • The new operator creates the Scanner object • Once created, the Scanner object can be used to invoke various input methods, such as: answer = scan.nextLine(); Reading Input • The Scanner class is part of the java.util class library, and must be imported into a program to be used • The nextLine method reads all of the input until the end of the line is found • The details of object creation and class libraries are discussed further on Friday Input Tokens • Unless specified otherwise, white space is used to separate the elements (called tokens) of the input • White space includes space characters, tabs, new line characters • The next method of the Scanner class reads the next input token and returns it as a string • Methods such as nextInt and nextDouble read data of particular types Flow of Control • Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence • Some programming statements allow us to: decide whether or not to execute a particular statement execute a statement over and over, repetitively • These decisions are based on boolean expressions (or conditions) that evaluate to true or false • The order of statement execution is called the flow of control Conditional Statements • A conditional statement lets us choose which statement will be executed next • Therefore they are sometimes called selection statements • Conditional statements give us the power to make basic decisions • The Java conditional statements are the: if statement if-else statement switch statement The if Statement • The if statement has the following syntax: if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped. Logic of an if statement condition evaluated true statement false Boolean Expressions • A condition often uses one of Java's equality operators or relational operators, which all return boolean results: == != < > <= >= equal to not equal to less than greater than less than or equal to greater than or equal to • Note the difference between the equality operator (==) and the assignment operator (=) The if Statement • An example of an if statement: if (sum > MAX) delta = sum - MAX; System.out.println ("The sum is " + sum); • First the condition is evaluated -- the value of sum is either greater than the value of MAX, or it is not • If the condition is true, the assignment statement is executed -- if it isn’t, it is skipped. • Either way, the call to println is executed next Indentation • The statement controlled by the if statement is indented to indicate that relationship • The use of a consistent indentation style makes a program easier to read and understand • Although it makes no difference to the compiler, proper indentation is crucial The if Statement • What do the following statements do? if (top >= MAXIMUM) top = 0; Sets top to zero if the current value of top is greater than or equal to the value of MAXIMUM if (total != stock + warehouse) inventoryError = true; Sets a flag to true if the value of total is not equal to the sum of stock and warehouse • The precedence of the arithmetic operators is higher than the precedence of the equality and relational operators Logical Operators • Boolean expressions can also use the following logical operators: ! && || Logical NOT Logical AND Logical OR • They all take boolean operands and produce boolean results • Logical NOT is a unary operator (it operates on one operand) • Logical AND and logical OR are binary operators (each operates on two operands) Logical NOT • The logical NOT operation is also called logical negation or logical complement • If some boolean condition a is true, then !a is false; if a is false, then !a is true • Logical expressions can be shown using a truth table a !a true false false true Logical AND and Logical OR • The logical AND expression a && b is true if both a and b are true, and false otherwise • The logical OR expression a || b is true if a or b or both are true, and false otherwise Logical Operators • Expressions that use logical operators can form complex conditions if (total < MAX+5 && !found) System.out.println ("Processing…"); • All logical operators have lower precedence than the relational operators • Logical NOT has higher precedence than logical AND and logical OR Logical Operators • A truth table shows all possible true-false combinations of the terms • Since && and || each have two operands, there are four possible combinations of conditions a and b a b a && b a || b true true true true true false false true false true false true false false false false Boolean Expressions • Specific expressions can be evaluated using truth tables total < MAX found !found total < MAX && !found false false true false false true false false true false true true true true false false Short-Circuited Operators • The processing of logical AND and logical OR is “short-circuited” • If the left operand is sufficient to determine the result, the right operand is not evaluated if (count != 0 && total/count > MAX) System.out.println ("Testing…"); • This type of processing must be used carefully The if-else Statement • An else clause can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; • If the condition is true, statement1 is executed; if the condition is false, statement2 is executed • One or the other will be executed, but not both Logic of an if-else statement condition evaluated true false statement1 statement2 The Coin Class • Let's examine a class that represents a coin that can be flipped • Instance data is used to indicate which face (heads or tails) is currently showing Indentation Revisited • Remember that indentation is for the human reader, and is ignored by the computer if (total > MAX) System.out.println ("Error!!"); errorCount++; Despite what is implied by the indentation, the increment will occur whether the condition is true or not Block Statements • Several statements can be grouped together into a block statement delimited by braces • A block statement can be used wherever a statement is called for in the Java syntax rules if (total > MAX) { System.out.println ("Error!!"); errorCount++; } Block Statements • In an if-else statement, the if portion, or the else portion, or both, could be block statements if (total > MAX) { System.out.println ("Error!!"); errorCount++; } else { System.out.println ("Total: " + total); current = total*2; } The Conditional Operator • Java has a conditional operator that uses a boolean condition to determine which of two expressions is evaluated • Its syntax is: condition ? expression1 : expression2 • If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated • The value of the entire conditional operator is the value of the selected expression The Conditional Operator • The conditional operator is similar to an if-else statement, except that it is an expression that returns a value • For example: larger = ((num1 > num2) ? num1 : num2); • If num1 is greater than num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger • The conditional operator is ternary because it requires three operands • How would you rewrite the above using an if/else statement? Nested if Statements • The statement executed as a result of an if statement or else clause could be another if statement • These are called nested if statements • An else clause is matched to the last unmatched if (no matter what the indentation implies) • Braces can be used to specify the if statement to which an else clause belongs The switch Statement • The switch statement provides another way to decide which statement to execute next • The switch statement evaluates an expression, then attempts to match the result to one of several possible cases • Each case contains a value and a list of statements • The flow of control transfers to the statement associated with the first case value that matches • We do not have time to cover the switch statement this week Problem Solving • The purpose of writing a program is to solve a problem • Solving a problem consists of multiple activities: Understand the problem Design a solution Consider alternatives and refine the solution Implement the solution Test the solution • These activities are not purely linear – they overlap and interact Problem Solving • The key to designing a solution is breaking it down into manageable pieces • When writing software, we design separate pieces that are responsible for certain parts of the solution • An object-oriented approach lends itself to this kind of solution decomposition • We will dissect our solutions into pieces called objects and classes Object-Oriented Programming • Java is an object-oriented programming language • As the term implies, an object is a fundamental entity in a Java program • Objects can be used effectively to represent realworld entities • For instance, an object might represent a particular employee in a company • Each employee object handles the processing and data management related to that employee Objects • An object has: state - descriptive characteristics behaviors - what it can do (or what can be done to it) • The state of a bank account includes its account number and its current balance • The behaviors associated with a bank account include the ability to make deposits and withdrawals • Note that the behavior of an object might change its state Classes • An object is defined by a class • A class is the blueprint of an object • The class uses methods to define the behaviors of the object • The class that contains the main method of a Java program represents the entire program • A class represents a concept, and an object represents the embodiment of that concept • Multiple objects can be created from the same class Objects and Classes A class (the concept) An object (the realization) Bank Account John’s Bank Account Balance: $5,257 Multiple objects from the same class Bill’s Bank Account Balance: $1,245,069 Mary’s Bank Account Balance: $16,833 Inheritance • One class can be used to derive another via inheritance • Classes can be organized into hierarchies Account Charge Account Bank Account Savings Account Checking Account