CS211 Java Bootcamp ------------------------------------------------------------------------------- + Help on Java: - see Java Resources link on http://www.cs.cornell.edu/courses/cs211/2002sp/ - contains link to Java tutorial http://java.sun.com/docs/books/tutorial/ + Help on IDEs and CodeWarrior: - On Java Tutorial Site, "Your First Cup of Java: Detailed instructions to help you run your first program: Win32, UNIX, Mac" - "Development Environments/Compilers" on CS211 in Java Resources - CodeWarrior link on CS211 + CS100J: http://www.cs.cornell.edu/courses/cs100j/2001fa/ (Notes and Exams will give you sample programs and problems) + Books: - easier: Java in a Nutshell (on CS211 site in Syllbus) - harder: The Java Programming Language - hardest: The Java Language Specification ------------------------------------------------------------------------------- Language Elements: + LANGUAGE: write sentences (statements) out of words (tokens), which are formed from an alphabet (character set) + PROGRAM: write paragraph (program) ------------------------------------------------------------------------------- Character Set: + UNICODE: - 16 bit encoding - store virtually every character out there + http://www.unicode.org/ + Java will automatically understand ASCII + enter character anywhere in program as \uxxxx ------------------------------------------------------------------------------- Comments: + type 1: single line: // I am a comment + type 2: multi-line: /* I am a comment */ nesting allowed: /* /* .... */ */ + type 3: doc comment (see Java Resources for Java Doc info) ------------------------------------------------------------------------------- White Space: + blanks, tabs ignored by Java compiler + use as many as you want + do NOT split token ------------------------------------------------------------------------------- Tokens: + reserved word/keyword (see lists in many books) + indentifier: - name/variable that refers to something - must begin with letter, underscore (_), or currency symbol ($) - may contain any number of digits, letters, _s, curreny symbols after the first character - Java is case sensitive! - must not use reserved words + primitive data types: - eight types (boolean, char, byte, short, int, long, float, double) - the values are also called CONSTANTS or LITERALS - why "primitive?" one solid value (not composite) - typically use boolean, int, double, char + boolean: true, false (no 0s and 1s allowed!) + char: Unicode characters - use 'character' (ex) char c = 'X'; - escape characters: \t (tab), \n (newline), \" ("), \' ('), \\ (\) - can convert chars to ints, and vice-versa + int: -2147483648 to 2147483647 + double: - use decimal point (.) (ex) .10 1. 1.0 - use scientific notation (ex) 1e-6 1.23E02 + strings: - technically objects (use String class) - string literal: "characters" - empty string: "" - can include escape characters + operators: - mostly borrowed from C/C++ - increment/decrement ex) x=x+1 could be written as x++ or ++x ex) a=1;b=a++; means that b gets the current value of a, then a increments - modulus (%) (remainder operator) ex) 4 % 3 gives 1 - beware of = (assign) vs == (equals)! - instanceof (see Weiss -- we didn't use this in CS100) - object access (.) - array element access ([]) - object creation (new) - casting ( () ) + punctuation: - ( ) expressions, methods - ; ending statements - { } blocks of statements ------------------------------------------------------------------------------- Statements: + empty: ; - just a semicolon - means "simply succeed and move to next statement + block: - collection of other statements inside { } - treated as if it were a "subprogram" with its own variables if they're declared inside + expression - legal expression statements are assignments (see below), increments/ decrements, method calls (see below), and object creation - combine constants with operators - precedence: some operators "come before" others - associativity: operators "work" left to right or right to left ex) 1 + 1; 2 * 2 - 4; // technically means (2*2) - 4 because of precedence 2 - 1 - 3; // technically means (2-1) - 3 due to associativity - use () to force some expressions to evaluate first ex) (1 + 1); // () not needed 2 * (2 - 4); 2 - (1 - 3); - beware of mixing types! ex) System.out.println(1/2) yields 0, not 0.5 - mixing doubles and ints makes doubles ex) System.out.println(1.0/2) yields 0.5 - use CAST to force different value syntax: (type) expression ex) System.out.println( (int) 9.8) yields 9 (an integer) + declaration: - variables (identifiers) can hold values - values can be primitive and reference types - Java is strongly typed, so must tell Java about variables before using syntax: variabletype var ; ex) char c; int value; - cannot redeclare a variable once it is declared inside { } + assignment: - special kind of expression statement - store value in a variable that's been declared - cannot use variable until it's declared! - syntax: declaredvar = value - the value's type MUST match the variable's type ex) int x; x = 1; - shortcut to INITIALIZE (declare and assign) variable: syntax: type var = value ex) int y = 7; - use final to make a constant: final int x = 1; (cannot change now!) + labeled: - name a labeled statement - syntax: label:statement (avoid this!) + Method Call - special kind of expression statement - something1(something2) has the syntax name(expression) - arguments can be empty - arguments evaluated left to right before method body ex) System.out.println("Hello"); + object creation (later) + selection (next) + repetition (next) + others: break, continue, return, synchronized, throw, try (you'll see return in methods) ------------------------------------------------------------------------------- Conditions: + use if, if-else, if-else if, switch (see Java books for switch) + syntax: if (c) // if c is true s; // do s // otherwise, skip this statement if (c) // if c is true s1; // do s1 else // otherwise s; // do s2 + other varieties: if (c1) s1 else if (c2) s2 // no else needed! if (c1) s1; else if (c2) s2; else s3; + can have as many else-ifs as you wish + indent statements, but entire body counts as SINGLE statement! (indenting does not make a new statement, just improves clarity) + can do multiple statements under each condition: - use statement block - { statements } + language elements: - if, else are keywords - conditions? must evaluate to true or false (Boolean) o relations: < (less than) > (greater than) <= (less than or equal) > (greater than or equal) == (equal, but do NOT use =) != (not equal) o logic: && (and) || (or) ! (not) o values: true false ------------------------------------------------------------------------------- Repetition: + use while, do-while, for while(condition) s; while(condition) { statements; } do { statements; } while(condition) for(initializations; conditions; increments) { statements; } + ex) int i = 1; while ( i < 4) { becomes for (int i = 1 ; i < 4 ; i++ ) System.out.println(i); System.out.println(i); i++; } ------------------------------------------------------------------------------- Methods: + syntax: modifiers returntype name(arguments) [throws exceptions] { statements; } - must access a method from a class or from within a class! + Arguments (formal parameters): - Java is strongly typed - arguments is composed of series of inputs with form: type1 var1, type2 var2, ... - can also have NO arguments -- use (), not (void) ex) System.out.println() - Call by value: + value of actual parameter copied into formal parameter + method can NOT change the value of an actual parameter + Name: - use a legal identifier - name should be an action + Return type: - methods RETURN either a value or nothing (1) nothing to return: - use void keyword - may use return; statement to break from a void method (2) value to return: - use return expression; statement somewhere in method - Java is strongly typed, so type of returned value must be the returntype + Local variables: - variables declared inside a method - same rules as formal parameters, but declared after formal params - variables cannot be "seen" (are invisible) to other methods + think "statement block": header { stuff; } + the "stuff" may have declarations which are local (visible) only in the block! + Overloading: - write several methods with the same name - change order of arguments, types of arguments, number of arguments, or any combination of these. - the following do NOT constitute method overloading: + Changing *just* the return type + Changing *just* the names of the formal parameters + throws exceptions (see textbooks -- not really covered in CS100) + Modifiers: - privacy: public, protected, , or private - class method (access w/o object): static - no overriding (inheritance): final - others: native, synchronized (not discussed in CS100) ------------------------------------------------------------------------------- Classes: + blueprint for creating objects + except for import&package statements, your code goes into a class + syntax: modifiers class { fields; constructors; methods; } (CS100) - other things inside a class: inner classes, static/instance initialization blocks (not CS100) - fields and methods called MEMBERS + field syntax: - modifiers (privacy, static, final) type name (= expression) - a field may use another as long as it's declared beforehand - fields get default values of "zero" ints: 0, doubles: 0.0, chars: ASCII code 0 or \u0000, boolean: false all reference variables: null, Strings (which are objects): null + method syntax: - must write methods in a class! - every method can see any other method in the same class in any order + constructor: - resemble a method, but no return type written syntax: modifiers (privacy) name(arguments) { body } - constructors do return a reference to a newly created object - every class has at least one constructor - if you do not give a constructor, Java assumes name() {} (called the "empty constructor) - the first statement in the constructor MUST either + call a constructor of the same class with this(arguments) + call the super class constructor with super(arguments) (inheritance) + not have a super(...) or this(...), in which case, the constructor will automatically call super() (inheritance...for a class that does not extend from another, Java calls class Object) example: class Person { private String name; public Person(String n) { name=n; } public toString() { return name; } public addLastName(String ln) { name+=ln; } ------------------------------------------------------------------------------- Creating Objects and References: + to create an object (which is an instance of a class), use a constuctor call with new Classname(arguments) + this code is a kind of statement: ex) new Thing(1,2,3); + Java does not allow you to "store" the object in a variable + you need to use a variable that has the type of the object REFERENCE VARIABLE: store address of the object ex) Thing x = new Thing(); - x is a variable of type Thing - x stores the address of a newly created Thing - if you print x, you'll see the address value (Thing@....) ex) class One { public One() { } // is this necessary? } class Two { public void something() { One x; // does x have a value? new One(); // what happens here? x = new One(); // what happens now? } } + toString: - to print the contents of an object, include a public String toString() method - return a String that describes the object's contents ex) public String toString() { return "Name: "+name; } (assuming you have a field called name) class Thing1 { } // using default constructor Thing1(){} class Thing2 { public String toString() {return "I am a Thing2!";} } public class Example3 { public static void main(String[] args) { // new Thing1(); new Thing2(); // System.out.println(new Thing1()); // Thing1 t1 = new Thing1(); Thing2 t2 = new Thing2(); // System.out.println(t1); System.out.println(t2); } } + Aliases: - reference variables store an address of an object - so, changing the content of a ref var means storing the address of a different object ex) Person boss; Person p1 = new Person(); Person p2 = new Person(); boss = p1; + passing references: - methods have have formal parameters, which are essentially local variables - variables store values - "passing an object" to a method means passing a ref - "returning an object" from a method means returning a ref private String name; public Person(String n) { name = n; } public String toString() { return name; } } public class Example { public static void main(String[] args) { test1( new Person("Borknagar") ); System.out.println(test2()); } private static void test1(Person p) { p = new Person("Shagrath"); } private static Person test2() { return new Person("Dani"); } } + this (keyword): - represents a reference to the CURRENT object example) class Person { private String name; // name of current Person private Person friend; // friend of current Person public Person(String name) { this.name = name; } // Set current Person's friend: public void makeFriends(Person friend) { this.friend = friend; friend.friend = this; } } ------------------------------------------------------------------------------- Scope: + scope essentially means visibility or accessibility + overall structure you've seen: class { fields; methods(params) { vars; { blockvars; } } } + scoping rules for code WITHIN a class: - fields can access "previous" fields but not see "ahead" (fields are initialized top-down, left-to-right) - all methods see all the fields - all methods can see each other regardless of order - all members in a class can see eachother regardless of modifier + scoping rules for code WITHIN a method - parameters and variables are declared within the method - they cannot be seen OUTSIDE of the method + thus, params and vars declared in method are often called LOCAL VARIABLES + their names, values, and types are inaccessible outside the method) + they can use the same names as fields, because local variables are not seen by the class! + If Java cannot find a local var in a method, then Java looks for a field + they CAN be see by block statements inside the method if declared before the block + scoping for a given block: - variables can be declared inside a block if not declared OUTSIDE (and thus, before) the block - variables declared inside a block do NOT exist outside that block (which summarizes the entire scope issue in the first place!) - blocks can be re-initialized for loops (loop essentially repeat a block) example) class blah { int x1=10; int x2=17; String method1(double x1) { if (x1 > 0) { int x2 = 1; } { boolean x2 = true; } return method2(x1+x2); } String method2(double x2) { return "the value is: "+(x2+x1); } } public class scope0 { public static void main(String[] args) { System.out.println(new blah().method1(1)); } } // output: 28 ------------------------------------------------------------------------------- Object Literals: + we don't really discuss much in CS100, but useful to know! + null: value that represents the absence of an object ("no object") ex) Thing t = null; - use null when you need to use a reference variable before creating an object since variables must have values before you use them - also shows up as default value for fields that are references + String literals: "characters", creates a String object automatically - must be on one line - use + to add Strings together + Class Class (yes, there is such a thing) + anonoymous inner class ------------------------------------------------------------------------------- Information Hiding and Static: + make fields and members used only in the class private + everything else is public (but not variables inside a method!) + public class members can be accessed from outside the class + private class members can NOT be access from outside the class but objects created from the same class can indeed access the members + static means you can access a member w/o creating an object - does NOT mean "unchanging!" - use Classname.member for access - all objects will share the same static member, so you can also use ref.member to access example -- see also "Mixing.java" in 10/18, CS100) class Student { private String name; private static int count; public static int currentYear; public static final int GRADYEAR = 2005; public Student(String name) { this.name=name; count++; } public static int getCount() { return count; } } public class Course { public static void main(String[] args) { System.out.println(Student.GRADYEAR); Student s1 = new Student("Dani"); Student s2 = new Student("Shagrath"); Student.currentYear = 2001; System.out.println(s2.currentYear); System.out.println(Student.getCount()); } } /* Output: 2005 2001 2 */ ------------------------------------------------------------------------------- Strings and Characters: + characters (see Tokens above) + collections of characters + objects in Java + string literal: "stuff" (saves hassle of calling a constructor) + operations: - "stuff1"+"stuff2" -> "stuff1stuff2" - "stuff"+primitive type promotes to String - must put String on ONE line (no continuation character!) + constructors? String s1 = new String(); // create empty string String s2 = new String("stuff"); // create string of "stuff" char[] tmp = {'a','b','c'}; // uses an array String s3 = new String(tmp); // create string from chars + so, what is a string literal? an instance of class String -- namely, a shortcut from calling a constructor! + immutable -- once created, cannot change! see StringBuffer class for mutable strings + Resemblence of Strings to arrays: - index of characters starts count at ZERO - find number of characters with $length()$ (not $length$) ex) string: ABCD indicies: 0123 + String methods (see 10/18 examples in CS100J Fall 2001) + equals: - to compare contents of 2 Strings s1 and s2: s1.equals(s2) - why not ==? == tests equality of references, not contents! - so, s1==s2 test if s1 and s2 refer to the same object - sometimes == works...why? == will check contents when comparing 2 String literals only ------------------------------------------------------------------------------- Arrays: + arrays are objects! + all elements must have the same type (or class) + indicies must be integers or expressions that evaluate to integers + most basic array is a 1-D collection of items + when we say ARRAY, we mean 1D array in Java + creating arrays: - declare: type[] name; type name[]; - assign: name = new type[size]; - shortcut version: type[] name = new type[size] (more "versions" show up later) + important notes/features: - [] is operator and has highest precedence (after the .) - can declare arrays in same statement but be careful: ex) int a[], b; -> b is NOT an array - why use new? arrays are objects - size is number of elements (must be integer or integer expression >= 0) - labeling of indicies starts at zero! - if you attempt to access index that does not exist, Java complains with out-of-bounds exception (not all languages do this!) - can find length automatically with arrayname.length - all values in array are "zeros" by default (just like instance variables) + initializer lists: - handy way to creating an array and storing small amount of values: type[] var = {val,val,...}; <- the $;$ is mandatory here! ^^^^^^^^^^^^^^ INITIALIZER LIST - essentially a shortcut, but not useful as a trick to "pass arrays": return {1, 2, 3}; won't work (use anonymous array) - formal way to write as an anonymous array: typ[] var = new type[] {list of values}; ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ANONYMOUS ARRAY - may use anonymous arrays to pass a ref to an array WITH values + objects with arrays: - one way of "faking" a collection of different types - some classes may have fields as arrays - initialize size in the constructor + arrays of objects: - think of the syntax type[] + this syntax implies all kinds of types! + can be primitive types, can be classes? - examples: Worker[], Tray[], Blah[], etc - array of objects means ARRAY OF REFERENCES + elements hold references, not objects! + need to create objects for each element of array + default values are null + need to say Thing[0] = new Thing(...); Thing[1] = new Thing(...); etc - to access members of objects "in" an array (the refs are in the array), + use name[index].member + the [] "operates" before the . + multidimensional arrays - rectangular array concept: type[][][] var = new type[size1][size2][size3] - array of array concept: type[][][] var = new type[size1][][] then assign arrays to "2nd" and "3rd" dimensions of var (see aoa examples from CS100J FALL 2001) ------------------------------------------------------------------------- Inheritance: (13) Inheritance + subclass extends a superclass (only single inheritance is allowed) + order of creation: set all fields to default values ("zeros"), access the constructor of the subclass, call a constructor of the same class with $this(...)$ (if necessary), call the superclass constructor (with $super(...)$ or $super()$, by default), work all the way up to $Object$, and then "come down" (do the field assignments and the rest of the constructor execution for each superclass until returning to subclass) + rules for visibility and access - fields are accessed by the reference type for "outside" call - methods are accessed by the object type for "outside" call - public/protected methods and fields are inherited unless written in the subclass (called overriding for methods and shadowing for fields) - private fields and methods are accessed from the SAME class that they are called (they "bind" to the current class) - private members technically do NOT inherit, but may be indirectly accessed using a public/protected member which DOES inherit - methods will access the field from the class in which the executed method is written - static members are technically hidden (cannot be overriden): so, they can be inherited, but are accessed through the ref type, not object type + $super.$: access a superclass member (variable, method), unless that member is NOT visible + $Object$: all classes inherit from $Object$ - $toString$, $getClass$, $equals$ methods + $abstract$ classes - used to differentiate class hierarchies and provide templates to write classes - have at least 1 abstract method (a method with only a header and no body) - cannot create objects from abstract classes! - can use abstract classes as reference types! - members will inherit from abstract classes, but the methods must be overriden in a subclass if you want the subclass to be "concrete" (to be able to make an object) ------------------------------------------------------------------------------- Polymorphism: + a subclass object may have a superclass reference type + methods accessed from the actual class type of the object (dynamic lookup/binding) + a way of "mixing" related types + typical use is collecting objects from an inheritance hierarchy in an array, list, Vector, or other collection ------------------------------------------------------------------------------- MATLAB + haha...Just kidding :-) -------------------------------------------------------------------------------