{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

CS 107 Lecture Part 1

CS 107 Lecture Part 1 - C8107 LECTURE NOTES PART 1 FALL...

Info iconThis preview shows pages 1–12. Sign up to view the full content.

View Full Document Right Arrow Icon
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Background image of page 2
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Background image of page 4
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Background image of page 6
Background image of page 7

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Background image of page 8
Background image of page 9

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Background image of page 10
Background image of page 11

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Background image of page 12
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: C8107 LECTURE NOTES PART 1 FALL 2008 JAVA DATA TYPES DATA TYPE MEMORY USAGE W byte lbyte -l28 to 127 short 2 bytes 92,768 to 32,767 int 4 bytes —2,147,483,648 to 2,147,483,647 long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 float 4 bytes approx :t3.4E+38 to $1.4E-45, with 5-7 significant digits double 8 bytes approx i1.7E+308 to i4.9E—324, with 13-15 Sig. digits char 2 bytes (Unicode) E.g., char 0 = 'a'; (or, values 0 to 65535) boolean 1 byte true, false STRINGS String s=“Hello"; The "String" data type is really a class, not one of Java's 8 primitive data types. EXAMPLES int's: —203241, 2, 10 (integers without L or casts, are treated as int's) lung's: 62231288618L, 2L (forces 2 to be treated as a long, in 8 bytes) float‘s: 3.14F, 6.023e23F (scientific notation, 6.023x1023) double's: 3.14 (decimals without F, are treated as double's), 1 1.41212121D Note: When you use numerical “literals" (specific numbers), you can add letter suffixes such as "L" or "F" or "D", to specify the data type of the literal. DECLARING AND INITIALIZING A VARIABLE * In Java, a variable MUST be "declared" (a.k.a. "defined") before you use it. That is, you must specify its data type before you use it. * "Initializing" a variable, means giving it an initial (first) value. * You can NOT re—declare a variable inside a program segment. Java will generate an error. int i; //declare i = 10; //initialize int i = 10; //shortcut, declare and initialize in one step N I ARITHMETIC OPERATORS FOR TWO NUIVIERICAL VALUES: if ( x == 2 ) if ( x != 2 ) FOR TWO STRING VALUES: if ( s.equals(t) ) if ( ! s.equals(t) ) FOR TWO REAL NUMBERS: + Z / Note: beware of integer—divided-by—integer division, e.g. 9/2 is 4, 1/2 is 0, etc. % modulus (remainder after a division, e.g. 8%3 is 2, 8.3%3.l is 2.1) RELATIONAL OPERATORS < <: > >2 7; 119i {f f a 9+ fl” M, ii LOGICAL OPERATORS f 3 ,1 " F 1 7‘ If g i L ’7 "'not" \I F i f r ‘« ES‘ lazy/fast "will”? ' if I at; ""and" _, II lazy/fast "0T" 5y; 3/6 E . / l "01'" J/me 5i 4 4! 4 r f xii $534.; 3,,Irgaireu. .g h .t ( )M‘LQ 5* g, ‘r’wrv‘fim = 4-541} A "XOer TESTING EQUALITY Careful! The = rarely works when comparing real numbers, because computers usually store real numbers with slight errors (because they must use a few bytes to store fiactions which are usually infinite in binary). So, to compare the other, then take the absolute value with small "tolerance" such as 1.06-6 . two real numbers, you should first subtract one from Math. abs, then see if the result is less than some a», Us" MIXED-MODE ASSIGNMENT WEAK VALUE INTO STRONG VARIABLE: NO PROBLEM Java casts the value automatically. double x = 3; //the 3 becomes 3.0, then x is set to 3.0 WARNING: In rare cases, be careful about losing precision. E.g., you can put a "long" value into a "float" variable, but don't forget that a "float" variable will only store 5—7 significant digits of accuracy. WHAT'S WEAK, WHAT'S STRONG? [strongest] double, float, long, int, short, byte [weakest] ALSO: char value automatically fits into the "stronger variables" int, long, float, double STRONG VALUE INTO WEAK VARIABLE: ERROR, UNLESS YOU CAST int i = (int) 3.88; //casts the double 3.88 to an int 3 WARNING: , Avoid "arithmetic overflow" and its garbage answers. Make sure glare stronger value is within the ? flu-.5,“ r'i allowable range of values for the weaker variable! W WHAT‘S WEAK, WHAT'S STRONG? t 4 Note that "char" is now in the list: UN” [weakest] byte, short, char, int, long, float , double [strongest] ALSO: You will need to explicitly cast when you put a byte or short value, into a char variable. b13f§fitfiflwflk ‘: i‘Ufld‘vW’“ View»); z a: i Mix/9. .« MIXED-MODE EXPRESSIONS Rule #1: For arithmetic between two of the same data type, the result will have that same data type. 3+6 is 9 3.0+6.0 is 9.0 Rule #2: For mixed-mode expressions, Java will "promote" the weaker data type to the stronger data type, and will then perform the arithmetic according to Rule #1. 4.0 * 6 is automatically promoted to 4.0 * 6.0, which is 24.0 by Rule #1. WARNING: The above Rules have some important consequences. * Be careful when you do integer—divided—by-integer division. E.g., 9/2 computes 4, not 4.5, because "int / int“ yields an "in " answer by Rule #1. E.g., 1/2 computes 0, not 0.5, by Rule #1. * Be careful when you do math, to ensure that the result won't be out of range for the data type involved, otherwise arithmetic overflow will occur and your answer will be incorrect. EXAMPLE OF OVERFLOW: 19000000 * 10000000 is incorrectly computed as 276fi47232, because "int * int" yields an "in " result, but the true answer is outside the allowable range of values for an "int", and therefore arithmetic overflow occurs. To do the math correctly, use instead 10000000L * 10000000 which is correctly computed as 100000000000000, because "long * int" is promoted to "long * long", yielding a "long" answer, and the true answer can fit into a "long", so no arithmetic overflow occurs. '1 vii , j; VJ {Qt-this amrufer in PEMDAS Computers use the same "PEMDAS" rules as in your algebra classes. 1. Parentheses. 2. Exponentiations. 3. Multiplications and divisions, going left to right. 4. Additions and subtractions, going lefi to right. SOME OF J AVA'S MATH FUNCTIONS AND CONSTANTS Math.sqrt(x) Math.pow(x,y) Math.abs(x) Math.exp(x) Math.;og(x) Math.ceil(x) Math.floor(x) Math.round(x) Math.cos(x) Math.sin(x) Math.tan(x) Math.max(x,y) Math.min(x,y) Math.PI Math.E square root of X. (Result always has data type "double".) x to the power of y. (Result always has data type "double".) absolute value. (Result is of same data type as the parameter.) e to the power of X, where e is 2.71828... (Result is "double".) natural logarithm, ln(x), for x>0. (Result is "double".) rounds upward to nearest integer. (Result is always "double".) rounds downward to nearest integer; (Result is always "d0uble".) rounds to nearest integer. (Result: int for dogs, long for doubles.) trigonometric fimctions. (Parameter is in radians.) larger value of x and y smaller value of x and y pi, 3.14159... e, 2.71828... CHOOSING NAMES RULES FOR IDENTIFIERS (names of variables, programs, functions, etc.) * Any length. * Contains only letters, digits, underscores, or dollar signs. * Can't begin with a digit. * Case sensitive. E.g., x and X are different variables. * Can't be one of Java's "reserved" words (such as "public", "static", "for", "While", etc.) DATA-TYPE CONVERSIONS PRIMITIVES --> PRIMITIVES Use the "east" operator: int i = (int) 3.14; PRIMITIVES --> STRINGS: String s = String.value0f(x); String t = x + ""; STRINGS --> PRIMIT IVES: byte b = Byte.parseByte("357"); short 5 = Short.parseShort("357"); int i = Integer.parselnt("357"); long j = Long.parseLong("357"); float f = Float.parseFloat("3.14"); double (1 = Double.parseDouble("3.14"); INCREASING/DECREASING VARIABLES 1 = i + 20; // increase i by 20. Shortcut: i+=20; j = j — 35; // decrease j by 35. Shortcut: j—=35; k++; // shortcut for "increase k by 1" n~—° // shortcut for "decrease n by 1" HOW TO DO USER-INPUT IN JAVA EXAMPLE OF SDSU.IO import sdsu.io.*; public class Progl { public static void main(String args) { String s = Console.readLine("Enter your name: "); int n = Console.readlnt("Enter your age: "); double x = Console.readDouble("Enter a real number: "); } } A WARNING ABOUT SDSU.IO: See detai ls on class website. EXAMPLE OF JAVA.IO import ja va.io.*; public class Prog2 éublic static void main(String args) throws IOException { BufferedReader keybd=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter your name: "); String s = keybd.readLine(); System.out.print("Enter your age: "); int n = Integer.parselnt(keybd.readLine()); System.out.print("Enter a real number: "); double x = Double.parseDouble(keybd.readLine()); EXAMPLE OF "SCANNE " import ja public cl { public st { Scanne String String int n double va.util.*; ass Prog3 atic void main(String args) r input = new Scanner(System.in); $1 = input.next(); //get text up to first whitespace or newline 32 = input.nextLine(); //get text up to first newline = input.nextInt(); //get the next "int" in the input stream x = input.nextDouble(); //qet the next "double" in the input stream "IF" STRUCTURES #L if ( true—or—false-expression ) single—statement; #2. if ( true—or—false—expression ) { one—or—more-statements } #3. if ( true—or—false-expression ) { statement/s } else { statement/s } #4. Go down list of conditions until a "true" one, do ONLY its code, then exit the IF structure. if ( true—or-false-expression ) { statement/s } . else if ( true—or-false—expression ) { statement/s } else if ( true—or-false—expression ) { statement/s } else ' //"else" block is optional. //it runs if all conditions were false. { statement/s } "FOR" LOOPS for ( slotl ; slot2 ; slot3 ) { statement/s } RULES 1. Execute the statement in slotl. 2. Test the boolean expression in slot2. It will be either true or false. 3. * If it was false, then loop terminates. (Exit out of loop, go on with rest of program) * If it was true, then execute statement/s in loop's body, then execute slot3, then go to Step 2. EXAMPLE: COMMON USAGE: Repeat a block of code, a specific number of times. 1Q“ “3‘13“; id» 5*“2\‘bb (9] O for (int i=1; i<=lOO; i++) $.Stmim V q { 610101 H/fl, rrrrrr '/ bit 3 System.out.println("Your name"); gléé d } f $Mg 1% . 1 37 ,i EXAMPLE: fiwdf 19 i’r‘v‘s‘ (LN for ( int i=1; i<=19; i=i+3) { \ System.out.println(i); v\. } i \U x”? \b NESTED "FOR" LOOPS If you follow the steps on the previous page, when a FOR loop is inside the body of a different FOR loop, then you will notice the following special-effect: The innermost block of code in nested FOR loops, will execute once for EACH combination of value of the loops's counter variables. for (int i=1; i<=2; i++) { for (int j=2; j<=67 j=j+2) { System.out.println(i + " and " + j); } l . inner Mac/‘4 9% if“ 2 . Q Will output: W (WM/M “£11129“! 9‘6“ ’l and 2 and 4 and 6 and 2 01 y and 4 0f and 6 , ”1:! N Prl/ “ h /,/-»M* """" \\ r” ‘9 M, l for (int i=1; i<=3; i++) \ { \ for (int j=1; j<=i; j++) «x,\_\ i\ i ' \ System.out.println(i + " and " + j);/ NMNl—‘I—‘H af ‘3 ,,A,\' 4"} 9/ \A WONN /,.»! "V l . . ' 3 Will output. and and and and and and wmmNNH WNt—‘Nl—‘t—J H "WHILE" LOOPS while ( true—or-false—expression ) { statement/s } RULES 1. Test the boolean expression. 2. * If it was false, then loop terminates. (Exit out of loop, go on with rest of program.) * If it was true, then execute statement/s in loop's body, then go to Step 1. "no (DO/WHILE)" LOOPS do { statement/s } while ’ true—or—false—expression ); \ RULES 1. Execute the statement/s in the 2. Test the boolean expression (true or false). 3. * If it was false, then loop terminates. (Exit out of loop, loop's body. go on with rest of program.) * If it was true, then go to Step 1. MISC. A "while" loop is a "pre-test" 100 A ”do/while" loop is a "post—test' p. The loop's body will execute O or more times. ' loop. The loop's body will execute 1 or more times. ...
View Full Document

{[ snackBarMessage ]}