// APS101, Winter 2009: Lecture 4 (Jan. 15) // // Review: last time we learned all about // primitive types, and variables. // ex. boolean (true, false) true && ! true || !(true && !false) || (false || true) // ex. character values char c; // variable declaration c // gets initialized to a default value c = 'a'; // variable assignment // we also talked about typecasting: int i = (int) 2.9f double x = 2.9f // float is "promoted" to double float f = 2.9 // error! can't assign a double to a float // // Today will be an introduction to Strings, // objects, and method calls. // // what if we want to store more than just 1 character? // i.e., strings of characters (words and sentences). 'abc' // need to use Strings: non-primitive type // also called object type "abc" String = "abc"; String myString = "abc"; myString String s; s // objects are automatically initialized to null! "hello" + "world" // concatenation // concatenation operator: + "hello" + " world" "hello" + " " + "world" "hello" + '!' // can combine Strings with chars! 'a' + "bc" "12" + 3 "This lecture begins at " + 10 + "am." 10 + " is when this lecture begins" "this is true or " + false myString.length() // length() is a method in the String class. // how do we know this? Let's take a look at the Java API... // API = Application Programming Interface myString.charAt(0) myString.charAt(1) myString.charAt(2) myString.charAt(3) // error: index out of bounds! // Method calls: // objectName.methodName(args) // args = arguments (0 or more) // method length() has takes no arguments // method charAt(int index) takes one int argument // (we'll look at Strings in more detail later.) String s = "abc" s.length() length("abc") // doesn't work - incorrect syntax! "abc".length() "abc ".length() // spaces (and all other characters) count // // Another type of object: Date // ex. Halloween: October 31, 2009 -> 10/31/09 // this is a way of representing information Date d; // can't find the class import java.util.Date; // need to import it first Date d; d // initialized to null! like all other objects. d = 10/21/09 d = new Date() d // how to declare an object variable: // ; // how to initialize an object variable: // = new (args) Date d = new Date(); // can do it all on one line d d.getYear() d.getMonth() Date d1 = new Date(2008, 9, 31) d1 Date d1 = new Date(08, 9, 31) Date d1 = new Date(108, 9, 31) d1 d1.getMinutes() d1 Date d2 = new Date(109, 9, 31) d2 d2.after(Date d1) d2.after(d1) d1.after(d2) d2.compareTo(d1) d1.compareTo(d2) // comparison operator: == d1 == d2 d1 Date d2 = new Date(108, 9, 31) d1 d2 d1 == d2 // false! d1.equals(d2) // use the "equals" method to compare objects! "abc".equals("abc") "abc" == "abc" d1 = d2 d1 == d2 // the "==" checks if it's the SAME object // the "equals" compares the VALUES of the objects