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
Primitive Types, Strings, and Console I/O Variables, values, and Expressions The Class String Keyboard and Screen I/O Documentation and Style Reading => Section 1.2 1 Variables and Values Variables are memory locations that store data such as numbers and letters. The data stored by a variable is called its value. The value is stored in the memory location. A variables value can be changed. 2 Variables and Values public class Cows { public static void main (String[] args) { int barns, cowsPer, totalCows; barns = 10; Output: cowsPer = 6; If you have 6 cows per barn and totalCows = barns * cowsPer; 10 barns, then System.out.println ("If you have"); the total number of cows is 60 System.out.print(cowsPer); System.out.println(" cows per barn and"); System.out.print(barns); System.out.println(" barns, then"); System.out.print("the total number of cows is “); System.out.println(totalCows); } } 3 Variables and Values public class Cows Output: { If you have public static void main (String[] args) 6 cows per barn and { 10 barns, then int barns, cowsPer, totalCows; the total number of cows is 60 barns = 10; cowsPer = 6; totalCows = barns * cowsPer; System.out.println ("If you have"); System.out.println (cowsPer + " cows per barn and"); System.out.println (barns + " barns, then"); System.out.println ("the total number of cows is " + totalCows); } } 4 Variables and Values Variables: barns cowsPer totalCows Assigning values: barns = 10; cowsPer = 6; totalCows = barns * cowsPer; A variable must be declared before it is used. When you declare a variable, you provide its name and type. int barns, cowsPer, totalCows; A variable’s type determines what kinds of values it can hold, e.g., integers, real numbers, characters. 5 Syntax and Examples Variable declaration syntax: type variable_1, variable_2, …; Examples: int styleChoice, numberOfChecks; double balance, interestRate; char jointOrIndividual; A variable is declared just before it is used or at the beginning of a “block” enclosed in { }: public static void main(String[] args) { /* declare variables here */ : } 6 Types in Java In most programming languages, a type implies several things: A set of values A (hardware) representation for those values A set of operations on those values Example - type int: Values – integers in the range -2147483648 to 2147483647 Representation – 4 bytes, binary, “two’s complement” Operations – addition (+), subtraction (-), multiplication (*), division (/), etc. Two kinds of types: Primitive types Class types 7 Types in Java A primitive type: values are “simple,” non-decomposable values such as an individual number or individual character int, double, char A class type: values are “complex” objects a class of objects has both data and methods ‘November 10, 1989’ is a value of class type date (non-Java) “BIG bad John.” is a value of class type String 8 Java Identifiers An identifier is a name given to something in a program: a variable, method, class, etc. created by the programmer, generally Identifiers may contain only: letters digits (0 through 9) the underscore character (_) and the dollar sign symbol ($) which has a special meaning the first character cannot be a digit. 9 Java Identifiers Legal Examples: count name address count1 count2 count3 x y z i j k myFavoriteHobby My_Favorite_Hobby Illegal Examples: 1count _name 7-11 netscape.com util.* 10 Java Identifiers, cont. Identifiers can be arbitrarily long. Java is case sensitive i.e., stuff, Stuff, and STUFF are different identifiers. Keywords or reserved words have special, predefined meanings: 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 Keywords cannot be used as identifiers 11 Naming Conventions A common recommendation is to choose names that are helpful, or rather readable, such as count or speed, but not c or s. Sometimes short names are appropriate. Variables (of both class and primitive types): begin with a lowercase letters (e.g. myName, myBalance). multiword names are “punctuated” using uppercase letters. Class types: begin with an uppercase letter (e.g. String, Scanner). Primitive types: begin with a lowercase letter (e.g. int, float). 12 Primitive Types Four integer types: byte short int (most common) long Two floating-point types: float double (most common) One character type: char One boolean type: boolean 13 Primitive Types, cont. 14 Examples of Primitive Values Integer values: 0 -1 365 12000 Floating-point values: 0.99 -22.8 3.14159 5.0 Character values: `a` `A` `#` ` ` Boolean values: true false 15 Motivation for Primitive Types Why are there several different integer types? storage space operator efficiency More generally, why are there different types at all? reflects how people understand different kinds of data, e.g., letter vs. numeric grades makes code more readable (which is a big deal) helps prevent programmer errors 16 Assignment Statements An assignment statement is used to assign a value to a variable: int answer; answer = 42; The “equal sign” is called the assignment operator. In the above example, the variable named answer is assigned a value of 42, or more simply, answer is assigned 42. 17 Assignment Statements, cont. Assignment syntax: variable = expression ; where expression can be a literal or constant (such as a number), another variable, or an expression which combines variables and literals using operators 18 Assignment Examples Examples: int amount; int score, numberOfCards, handicap; int eggsPerBasket; char firstInitial; : score = 3; firstInitial = ‘W’; amount = score; score = numberOfCards + handicap; eggsPerBasket = eggsPerBasket - 2; => Some note that the last line looks weird in mathematics. Why? 19 Assignment Evaluation The expression on the right-hand side of the assignment operator (=) is evaluated first. The result is used to set the value of the variable on the left-hand side of the assignment operator. score = numberOfCards + handicap; eggsPerBasket = eggsPerBasket - 2; The distinction between the two steps is very important! 20 Simple Input Sometimes data is needed and obtained from the user at run time. Simple keyboard input requires: import java.util.*; or import java.util.Scanner; at the beginning of the file. 21 Simple Input, cont. A “Scanner” object must be initialized before inputting data: Scanner keyboard = new Scanner(System.in); To input data: eggsPerBasket = keyboard.nextInt(); which reads one int value from the keyboard and assigns it to the variable eggsPerBasket. 22 Simple Input, cont. import java.until.Scanner; Output: public class Cows Enter the number of barns: 10 { Enter the number of cows per barn: 6 public static void main (String[] args) Total number of cows is: 60 { int barns, cowsPer, totalCows; Suppose two cows per barn escape! Total number of cows is now: 40 Scanner kb = new Scanner(System.in); System.out.print(“Enter the number of barns: ”); barns = kb.nextInt(); System.out.pring(“Enter the number of cows per barn: ”); cowsPer = kb.nextInt(); totalCows = barns * cowsPer; System.out.println(“Total number of cows is: “ + totalCows); System.out.println(“Suppose two cows per barn escape!”); cowsPer = cowsPer – 2; totalCows = barns * cowsPer; System.out.println(“Total number of cows is now: “ + totalCows); } } 23 Command-Line Arguments Frequently input is provided to a program at the command-line. public class UseArgument { public static void main(String[] args) { System.out.print(“Hi, ”); System.out.print(args[0]); System.out.println(“. How are you?”); } } Sample interaction: % javac UseArgument.java % java UseArgument Alice Hi, Alice. How are you? % java UseArgument Bob Hi, Bob. How are you? 24 Command-Line Arguments Frequently multiple values are provided at the command-line. public class Use3Arguments { public static void main(String[] args) { System.out.print(“The first word is ”); System.out.print(args[0]); System.out.print(“, the second is ”); System.out.print(args[1]); System.out.print(“, and the third is ”); System.out.println(args[2]); } } Sample interaction: % javac Use3Arguments.java % java Use3Arguments dog cat cow The first word is dog, the second is cat, and the third is cow 25 Command-Line Arguments Command-line arguments can be numeric. public class IntOps { public static void main(String[] args) { int a = Integer.parseInt(args[0]); // Notice the variable declaration int b = Integer.parseInt(args[1]); // Notice the comments…lol int sum = a + b; int prod = a * b; int quot = a / b; int rem = a % b; System.out.println(a + " + " + b + " = " + sum); System.out.println(a + " * " + b + " = " + prod); System.out.println(a + " / " + b + " = " + quot); System.out.println(a + " % " + b + " = " + rem); } } Sample interaction: % javac IntOps.java % java IntOps 1234 99 1234 + 99 = 1333 1234 * 99 = 122166 1234 / 99 = 12 1234 % 99 = 46 26 Literals Values such as 2, 3.7, or ’y’ are called constants or literals. Integer literals can be preceded by a + or - sign, but cannot contain commas. Every integer literal is either of type int or type long. The type of an integer literal can be determined by…looking at it! 27 Integer Literal Type An integer literal is of type long if it is suffixed with an letter L or l; otherwise it is of type int. note that capital L is preferred Integer literals of type long: 2L 777L -372L 1996L 2147483648l 0l Integer literals of type int: 2 777 -372 1996 2147483648 0 28 Floating Point Literals Floating point literals: Can be preceded by a + or - sign, but cannot contain commas Can be specified in (a type of) scientific notation Examples: 865000000.0 can also be written as 8.65e8 0.000483 can also be written as 4.83e-4 The number in front of the “e” does not need to contain a decimal point, e.g. 4e-4 29 Floating Point Literal Type Every floating point literal is either of type float or type double. The type of a floating point literal can be determined by…looking at it! An floating point literal is of type float if it is suffixed with an letter F or f; otherwise it is of type double. Floating point literals of type float: 2.5F 8.65e8f 0.0f 3f +35.4f -16F -16.0F 4e-4F 30 Assignment Compatibilities Java is said to be strongly typed, which means that there are limitations on mixing variables and values in expressions and assignments. What is the type of the LHS and RHS for each statement? int x = 0; long y = 0; float z = 0.0f; int w; w x x y z y = = = = = = x; y; z; z; 3.6; 25; // // // // // // legal; what does it do? illegal illegal illegal illegal (3.6 is of type double) legal, but…why? 31 Assignment Compatibilities Sometimes automatic conversions between types do take place: short s; int x; s = 83; x = s; double doubleVariable; int intVariable; intVariable = 7; doubleVariable = intVariable; 32 Assignment Compatibilities, cont. In general, a value (or expression) of one numeric type can be assigned to a variable of any type further to the right, as follows: byte --> short --> int --> long --> float --> double but not to a variable of any type further to the left. Makes sense intuitively because, for example, any legal byte value is a legal short value. On the other hand, many legal short values are not legal byte values. 33 Assignment Compatibilities, cont. Example – all of the following are legal, and will compile: byte b = 0; short s; int i; long l; float f; double d; s = b; i = b; l = i; f = l; // This one is interesting, why? d = f; b = 10; 34 Assignment Compatibilities, cont. Example – NONE (except the first) of the following will compile: byte b; short s; int i; long l; float f; double d; d = 1.0; // This one compiles f = d; l = f; i = l; s = i; b = s; 35 Type Casting A type cast creates a value in a new type from an original type. A type cast can be used to force an assignment when otherwise it would be illegal (thereby over-riding the compiler, in a sense). Example: double distance; distance = 9.0; int points; points = distance; // illegal points = (int)distance; // legal 36 Type Casting, cont. The value of (int)distance is 9, but the value of distance, both before and after the cast, is 9.0. The type of distance does NOT change and remains double. What happens if distance contains 9.7? Any value right of the decimal point is truncated (as oppossed to rounded). 37 Type Casting, cont. A cast can be performed from any primitive type to any other primitive type, however… Remember to “cast with care,” because the results can be unpredictable. int x; long z = ?; // ? Could be a computation or input x = (int)z; 38 Characters as Integers Like everything else, each character is represented by a binary sequence. The binary sequence corresponding to a character is a positive integer. Which integer corresponds to each character is dictated by a standardized character encoding. Each character is assigned a unique integer code The codes are different for upper and lower case letters, e.g., 97 may be the integer value for ‘a’ and 65 for ‘A’ Some characters are printable, others are not Why should different computers and languages use the same code? ASCII and Unicode are the most common character codes. 39 Unicode Character Set Most programming languages use the ASCII character encoding. American Standard Code for Information Interchange (ASCII) (only) encodes characters from the north American keyboard uses one byte of storage Java uses the Unicode character encoding. The Unicode character set: uses two bytes of storage includes many international character sets (in contrast to ASCII) codes characters from the North American keyboard the same way that ASCII does Hey, lets google ASCII!!!! 40 Assigning a char to an int A value of type char can be assigned to a variable of type int to obtain its Unicode value. Example: char answer = ’y’; System.out.println(answer); System.out.println((int)answer); >y >121 See the program at: http://www.cs.fit.edu/~pbernhar/teaching/cse1001/charTest 41 Initializing Variables A variable that has been declared, but not yet given a value is said to be uninitialized. int x, y, z; x = y; x = z + 1; Some languages automatically initialize a variable when it’s declared, other languages don’t. Others (Java) initialize in some circumstances, but not in others. Variables declared to be of a primitive type are NOT automatically initialized. In other cases Java will initialize variables; this will be discussed later. 42 Initializing Variables Some languages report an error when a variable is used prior to initialization by the program. Sometimes at compile time, other times at run-time. Some languages won’t report an error, and will even let you use an uninitialized variable. In such cases the initial value of the variable is arbitrary! The program might appear to run correctly sometimes, but give errors on others. Java: The compiler will (try) to catch uninitialized variables. => Always make sure your variables are initialized prior to use! 43 Initializing Variables, cont. In Java, a variable can be assigned an initial value in it’s declaration. Examples: int count = 0; char grade = ’A’; // default is an A Syntax: type variable1 = expression1, variable2 = expression2, …; 44 Arithmetic Operations Arithmetic expressions: Formed using the +, -, *, / and % operators Operators have operands, which are literals, variables or sub-expressions. Expressions with two or more operators can be viewed as a series of steps, each involving only two operands. The result of one step produces an operand which is used in the next step. Java is left-associative. Most of the basic rules of precedence apply. Example: int x = 0, y = 50, z = 20; double balance = 50.25, rate = 0.05; x = x + y + z; balance = balance + balance * rate; balance = (balance + balance) * rate; 45 Expression Type An arithmetic expression can have operands of different numeric types. x + (y * z) / w Note that this does not contradict our rules for assignment. Every arithmetic expression has a (resulting) type. k = x + (y * z) / w; // Does this compile? Given an arithmetic expression: If any operand in the expression is of type double, then the expression has type double. Otherwise, if any operand in the expression is of type float, then the expression has type float. Otherwise, if any operand in the expression is of type long, then the expression has type long. Otherwise the expression has type int. 46 Expression Type, cont. Example: int hoursWorked = 40; double payRate = 8.25; double totalPay; Then the expression in the assignment: totalPay = hoursWorked * payRate is a double with a value of 500.0. 47 Operators with integer and floating point numbers See the program: http://www.cs.fit.edu/~pbernhar/teaching/cse1001/expressions http://www.cs.fit.edu/~pbernhar/teaching/cse1001/integralConversion 48 The Division Operator The division operator (/) behaves as expected. If one of the operands is a floating-point type then the result is of the same floating point type. 9.0 / 2 = 4.5 9 / 2.0 = 4.5 If both operands are integer types then the result is truncated, not rounded. 9/2 = 4 99 / 100 = 0 Note that the typing rules previously presented still apply! 49 The mod Operator The mod (%) operator is used with operands of integer type to obtain the remainder after integer division. 14 divided by 4 is 3 with a remainder of 2. Hence, 14 % 4 is equal to 2. The mod operator has many uses, including determining: If an integer is odd or even (x % 2 = 0) If one integer is evenly divisible by another integer (a % b = 0) Frequently we want to map (a large number of) m “items,” number 1 through m, into n>=2 buckets. 50 Example: Vending Machine A really bad example, with 3 good lessons: Requirements Iterative enhancement (spiral vs waterfall) Testing 51 Example: Vending Machine Program Requirements: The user enters an amount between 1 cent and 99 cents. The program determines a combination of coins equal to that amount. For example, 55 cents can be two quarters and one nickel. Largest denominations are given preference. => What are “requirements” anyway? Sample dialog: Enter a whole number from 1 to 99. The machine will determine a combination of coins. 87 87 cents in coins: 3 quarters 1 dime 0 nickels 2 pennies 52 Example, cont. Algorithm (version #1, in pseudo-code): 1. Input the amount from the user. 2. Find the maximum number of quarters in the amount. 3. Subtract the value of the quarters from the amount. 4. Repeat the last two steps for dimes, nickels, and pennies. 5. Print the amount and the quantities of each coin. Program Variables Needed: int amount, quarters, dimes, nickels, pennies; 53 Example, cont. Interpreted literally, the algorithm leaves some details: The user must be prompted for the amount. The original amount is changed (and hence lost) by the intermediate steps. So we add an additional variable: int amount, originalAmount, quarters, dimes, nickles, pennies; and update the algorithm. 54 Example, cont. Algorithm (version #2): 1. Prompt the user for the amount. 2. Input the amount. 3. Make a copy of the amount. 4. Find the maximum number of quarters in the amount. 5. Subtract the value of the quarters from the amount. 6. Repeat the last two steps for dimes, nickels, and pennies. 7. Print the original amount and the quantities of each coin. Typically pseudo-code is iteratively embellished or enhanced. 55 Example, cont. How do we determine the number of quarters in an amount? There are 2 quarters in 55 cents, but there are also 2 quarters in 65 cents. That’s because 55 / 25 = 2 and 65 / 25 = 2. How do we determine the remaining amount? Using the mod operator: 55 % 25 = 5 and 65 % 25 = 15 Similarly for dimes, nickels and pennies Pennies are simply amount % 5. 56 Example, cont. 57 Testing the Program The program should be tested with several different amounts. Test with values that give zero values for each possible coin denomination. Test with amounts close to: “Extreme” or “boundary condition” values such as 0, 1, 98 and 99. Coin denominations such as 24, 25, and 26. 58 Increment (and Decrement) Operators Used to increase (or decrease) the value of a variable by 1. count = count +1 count = count -1 The increment and decrement operations are easy to use, and important to recognize. The increment operator: count++ ++count The decrement operator: count- --count 59 Increment (and Decrement) Operators “Mostly” equivalent operations: count++; ++count; count = count + 1; count--; --count; count = count - 1; Unlike the assignment versions, however, the increment and decrement operators are operators and have a resulting value…huh? 60 Increment (and Decrement) Operators in Expressions After executing: int m = 4; int result = 3 * (++m); result has a value of 15 and m has a value of 5 After executing: int m = 4; int result = 3 * (m++); result has a value of 12 and m has a value of 5 61 Increment and Decrement Operator, Cont. Common code: int n = 3; int m = 4; int result; What will be the value of m and result after each of these executes? (a) result = n * ++m; (b) result = n * m++; (c) result = n * --m; (d) result = n * m--; 62 The Class String As we already have seen, a String is a sequence of characters. We’ve used constants, or rather, literals of type String: “Enter a whole number from 1 to 99.” “Number of quarters:” “I will output a combination of coins” 63 Declaring and Printing Strings Variables of type String can be declared and Initialized: String greeting; greeting = “Hello!”; Equivalent to the above: String greeting = “Hello!”; String greeting = new String(“Hello!”); Printing: System.out.println(greeting); 64 Inputting Strings Variables of type String can be input: String Word; System.out.print(“Enter a word:”); Word = keyboard.next(); System.out.print(“The word entered was: “ + Word); 65 Concatenation of Strings Two strings can be concatenated using the + operator: String s1 = “Hello”; String s2 = “Smith”; String s3; s3 = s1 + “ officer ”; s3 = s3 + s2; System.out.println(s3); Any number of strings can be concatenated using the + operator. 66 Concatenating Strings and Integers Strings can be concatenated with other types: String solution; solution = “The temperature is “ + 72; System.out.println (solution); Output: The temperature is 72 67 Classes Recall that Java has primitive types and class types: primitive types class types Primitive types have: simple, “atomic,” non-decomposable values operations (built-in, usually a symbol such as *, +, or -) used to declare variables Class types have: complex values, with structure methods (some built-in, others user-defined, usually a word) used to declare “objects” 68 The Class String String is a class type, which means it has methods. The length() method returns an int, which is the number of characters in a particular String object. String solution = “dog”; int count = solution.length(); You can use a call to method length() anywhere an int can be used. System.out.println(solution.length()); int X = 10; X = X * solution.length() + 3; 69 Positions in a String Each character in a String has its own position. Positions are numbered starting at 0. ‘J’ in “Java is fun.” is in position 0 ‘f’ in “Java is fun.” is in position 8 The position of a character is also referred to as its index. 70 Positions in a String, cont. 71 Indexing Characters within a String using Methods charAt(position) returns the char at the specified position Example: String greeting = "Hi, there!"; char ch1 = greeting.charAt(0); // Stores ‘H’ in ch1 char ch2 = greeting.charAt(2); // Stores ‘,’ in ch2 substring(start, end) returns the string from start up to, but not including, end String myWord; myWord = greeting.substring(4,7) // Stores the in myWord 72 String Methods There are many Java String methods. See the Java on-line documentation for more details! 73 Escape Characters How would you print the following? “Java” refers to a language. The following don’t work: System.out.println(“Java refers to a language.”); System.out.println(““Java” refers to a language.”); The compiler needs to be told that the quotation marks (“) do not signal the start or end of a string, but instead are to be printed. System.out.println(“\”Java\” refers to a language.”); 74 Escape Characters “Escape sequences” are used to print “problematic” characters. \” Double quote \’ Single quote \\ Backslash \n Newline (beginning of next line) \r Carriage return (beginning of current line) \t tab Each escape sequence is a single character even though it is written with two symbols. 75 Examples Examples: System.out.println(“abc\\def”); => abc\def System.out.println(“new\nline”); => new line char singleQuote = ‘\’’; System.out.println(singleQuote); => 76 ‘ Example of Class String 77 Examples Modify the previous program so that it prompts the user for a sentence and two words. The program will modify the sentence by replacing the first occurrence of the first word with the second word. Enter a sentence: Gosh sunny, it sure is sunny today. Enter a word: sunny Enter another word: bob Resulting sentence: Gosh bob, it sure is sunny today. 78 Number Constants Decimal 0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 0030 0031 0032 Binary 000000 000001 000010 000011 000100 000101 000110 000111 001000 001001 001010 001011 001100 001101 001110 001111 010000 010001 010010 010011 010100 010101 010110 010111 011000 011001 011010 011011 011100 011101 011110 011111 100000 Octal 0000 0001 0002 0003 0004 0005 0006 0007 0010 0011 0012 0013 0014 0015 0016 0017 0020 0021 0022 0023 0024 0025 0026 0027 0030 0031 0032 0033 0034 0035 0036 0037 0040 Hexidecimal 0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 000A 000B 000C 000D 000E 000F 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 001A 001B 001C 001D 001E 001F 0020 79