540 likes | 549 Vues
CS 200 Using Objects. Jim Williams, PhD. This Week. By Friday All Exam Conflict and Accommodations Requests Install Java (AdoptOpenJDK) & Eclipse Chap 2 Programs (P2): Due Thursday Lecture: Methods, Using Objects. Application: Temperature Conversion.
E N D
CS 200 Using Objects Jim Williams, PhD
This Week • By Friday • All Exam Conflict and Accommodations Requests • Install Java (AdoptOpenJDK) & Eclipse • Chap 2 Programs (P2): Due Thursday • Lecture: Methods, Using Objects
Application: Temperature Conversion (Degrees Fahrenheit – 32) x 5 / 9 = Degrees Celsius What symbols have different meanings in Java? What changes must be made to implement this equation in Java?
My List • X vs * • equals (==) vs assignment (=) • value is stored on the left hand side of assignment (=) operator • Variables: • name areas of computer memory, declare before use, declare type of data, initialize • Variable names: • start with letter, include letters numbers and _, but no spaces • Conventions: • camelCasing, spell out names • Semicolon at the end of statements
Methods • A named section of code that can be "called" from other code. • Lots of existing methods that you can use rather than writing yourself.
Method Demonstration • Name • Call vs Definition • Arguments vs Parameters • Local Variables vs Parameters • Returning values • Value of a method (returned value) • Testing Methods
Variables • Local • Variables declared within a method. • Must be initialized before reading from them. • Parameters • Variables declared within a method parameter list. • Initialized with arguments from the method call. Scope: Both are stored on the stack and only visible within the method they are declared.
Testing Methods Methods written to run test cases to help validate and debug your code. • Unit testing: Run multiple tests on a method • Regression testing: retest method after changes
API • Application Programmer Interface • Example: Search for "Java 8 Math" • Call class/static methods with the class name
API vs Code API:What Code: How
Calling Class/static Methods • Call class/static methods with the class name. double numInts = Math.pow( 2, 32); double root = Math.sqrt( 16); int num1 = 16; int num2 = 3; double result = num2 + Math.sqrt( num1);
Magic Numbers (bad practice) Numbers with unexplained meaning: public class H { public static void main(String []args) { double s = 71 / 39.3701; } }
Identifiers: Careful Naming • Names of classes, methods, variables and constants guide reader and follow course conventions. public class Height { public static void main(String []args) { final double INCHES_IN_METER = 39.3701; double heightInInches = 71; //or user input double heightInMeters = heightInInches / INCHES_IN_METER; } }
Number Systems Decimal 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 Binary 0, 1
Decimal 1 8 9 100 10 1 = 189
Binary 1 1 1 0 8 4 2 1 = 14
Binary 0 1 0 1 8 4 2 1 = 5
TopHat What is 10110 (binary) in decimal?
TopHat What is 19 (decimal) in binary?
Hexadecimal (group bits by nibble) 1000 = 8 1001 = 9 1010 = A 1011 = B 1100 = C 1101 = D 1110 = E 1111 = F 0000 = 0 0001 = 1 0010 = 2 0011 = 3 0100 = 4 0101 = 5 0110 = 6 0111 = 7 Learn the patterns to be able to recreate this.
What is 23 decimal in hexadecimal? • First convert to binary • Then group bits into nibbles, right to left • Convert nibbles to hexadecimal 16, 0, 4, 2, 1 0001 0111 17 (hexadecimal) Be able to convert between binary, decimal and hexadecimal.
TopHat What is 26 (decimal) in hexadecimal?
TopHat: What character is this? http://www.ssec.wisc.edu/~tomw/java/unicode.html Don't need to memorize unicode but be able to look up in a table. 0000 0000 0100 0010 Unicode: 0x003E 62 > 0x003F 63 ? 0x0040 64 @ 0x0041 65 A 0x0042 66 B 0x0043 67 C
What character is this? char letter = '\u0043'; http://www.ssec.wisc.edu/~tomw/java/unicode.html Unicode: 0x003E 62 > 0x003F 63 ? 0x0040 64 @ 0x0041 65 A 0x0042 66 B 0x0043 67 C
TopHat What will print out and why? System.out.println('a' + 'b');
Reference Types Contrast with Primitive types
Primitive vs Reference Data Type Analogy • Primitive: • Giving you a birthday present • Reference: • Giving you an invitation with the address to a party where you will receive a birthday present.
Primitive vs Reference Data Types Reference • Store a reference to another location in memory that contains value Integer num = 9; Integer num = new Integer(9); Primitive • Store value int i = 5; num i 5 9
Memory Areas: Stack vs Heap Heap • All references point to heap (objects on heap) Stack • Variables declared as local or parameters • May have primitive or reference data type
Demo: Java Visualizer int i = 3; Integer k = 4; Integer m = k; String s = "hi";
TopHat Is num2 on the stack or the heap? public static void main(String[] args) { int num = 4; Integer num2 = 5; }
Reference Types for Primitives • Useful to illustrate difference between primitive and reference variables • Wrapper classes contain helpful methods for the corresponding primitive data type. • e.g., search: Java 8 Integer • Later in course: useful for storing primitive data in generic data structures
int to String Conversions String weekNum = 3; String weekNum = "" + 3; Wrapper classes contain useful methods. String numStr = Integer.toString( 4); int num = Integer.parseInt( numStr);
Wrapper Classes • Boxing: Putting primitive into instance of wrapper class Integer num; num = new Integer( 8 ); • Unboxing: retrieve primitive from instance int num = num.intValue(); • auto-boxing/unboxing: when compiler inserts code to box/unbox.
TopHat: What is in the d3 variable? Double d1 = new Double(10); double d2 = d1; d1 = 14.1; Double d3 = d1; d1 = d2; System.out.println( d3);
Instance vs. Class (static) Methods Class (static) Methods • method definition has “static” modifier • use name of class when calling Math.max( 10, 20); Instance (non-static) Methods • method definition does Not have “static” modifier • use instance of class when calling String str = "hello"; char ch = str.charAt(1);
TopHat: Calling String methods String strA = "This is a string"; char aChar = strA.charAt( 3);
TopHat: Calling String methods String strA = "This is a string"; System.out.println( strA.substring( 3, 5));
Random Number Generator Random randGen; //Declare reference variable randGen = new Random(); //create instance // randGen.setSeed( 123); //set state int valueA = randGen.nextInt( 5); //get a value from 0 to 4 int valueB = randGen.nextInt( 5); int valueC = randGen.nextInt( 5);
TopHat Which expression will result in x having a value between 2 and 10, inclusive? Assume: Random rand = new Random();
Scanner • Import the Scanner class import java.util.Scanner; • Read from console/standard in Scanner in = new Scanner(System.in); • Read from a String Scanner input = new Scanner("123 cs200"); • Scanner Tutorial
Scanner Instance/object Methods • Use reference to access the same scanner. Scanner elephant = new Scanner(System.in); int num = elephant.nextInt(); String name = elephant.next(); String line = elephant.nextLine(); elephant.close();
Read In Values Using Scanner Whitespace: space, tab, newline Token: a sequence of non-whitespace characters. 14 23.0 hello This, is a sentence. 2nd line 3rd line 43
Using Scanner Scanner in = new Scanner( "Hello JAVA!\nlines\n"); • one long string of characters
Read tokens using Scanner • Read next token, skip leading whitespace, stop on whitespace after token next() //return a string nextInt() //try to return value as an int nextDouble() //try to return value as a double 14 23.0 \nhello\n 22, 16.5 cs200.
Misconception Scanner nextInt() method does NOT mean read in the next integer. nextInt() Means: read the next token and try to convert to be an int.
TopHat What are the values in word, num1 & num2? String note = "1.0 2\nAlex two words"; Scanner input = new Scanner( note); String word = input.next(); int num1 = input.nextInt(); double num2 = input.nextDouble();
Read a line using Scanner • Read up to and including next newline (\n), return everything prior to newline as a string (may be 0 length). nextLine() //returns a string 14 23.0 \nhello\n 22, 16.5 cs200.