Java Basics ala Goodrich Tamassia v v Everything
Java Basics (ala Goodrich & Tamassia) v v Everything is in a class A minimal program: public class Hello { public static void main(String[] args) { System. out. println(”Hello Computer Science”); } } q q q v Output? Where? Do colors mean something? Identify the pieces. . . Comp. Sci 100 E J 1. 1
Java Basics Objects v Every object is an instance of a class (which defines its type) v Objects contain data (state) and function (methods) v State q q v Stored in instance variables (fields, members) Can be base types (e. g. integers) or instances of (objects) of other classes Function q q Expressed as methods (subroutines, functions, procedures…) These define the behavior of objects of this class Comp. Sci 100 E J 1. 2
Java Basics v Declaring a Class: public class Counter { protected int count; Counter() { count = 0; } public int get. Count() { return count; } public void inc. Count() { count = count + 1; } public void dec. Count() { count = count – 1; } } Comp. Sci 100 E v Identify the methods by kind q Constructor q Accessor q Mutator (modifier) Note Syntax from this and previous examples q Braces q Semicolons q Parentheses q Indentifiers q. . . v J 1. 3
Java Basics v Class Modifiers q v Reserved Words q q q v Abstract, final, public, default May not be used as identifiers Shown in red by Eclipse and many of our examples See table in text (p 4) or in any Java text Comments q q q For human consumption: ignored by compiler Inline comments: // o Effective for rest (to end) of current line Block comments: /* */ o Effective between start and stop groups Comp. Sci 100 E J 1. 4
Java Basics v Primitive Types (base types) Built-in data types; native to most hardware q Note: not objects (will use mostly first four) byte boolean short int q double char v long float Constants (by example): boolean f = false; int i = 32769; double d = 0. 333333; char c = ’x’; Comp. Sci 100 E byte b = 33; short s = 21; long l = 289 L; float = 3. 141592 F; J 1. 5
Java Basics v Creating and Using Objects (Example) public class Example { public static void main(String[] args) { Counter c; // Counter defined on a previous slide Counter d = new Counter(); c = new Counter(); System. out. println(”c = ” + c + ” d = ” + d); c. inc. Count(); d. dec. Count(); System. out. println(”c = ” + c + ” d = ” + d); d = c; // what does this really mean? ? ? c. inc. Count(); d. inc. Count(); System. out. println(”c = ” + c + ” d = ” + d); } } Comp. Sci 100 E J 1. 6
Java Basics v v String Objects q string is a sequences of characters (char) q o Unicode (16 bit) String is a built-in class o Constants: ”this is an example” String Concatenation (+) String s = ”Happy birthday to you. ”; s = s + ”n” + s; System. out. println(s); // what ? Comp. Sci 100 E J 1. 7
Java Basics v Object References q q q q When creating object with new, get location or address of new object Typically assign this to a reference variable: Counter c = new Counter(); Every object reference variable refers to object or null Null is an important value that indicates object not created or not available. Can have multiple references to same object Access members of class using dot operator (“. ”). Counter c = new Counter(); c. inc. Count(); May have multiple methods with same name but different signature: e. g. : c. inc. Count(); c. inc. Count(5); Comp. Sci 100 E J 1. 8
Java Basics v Instance Variables q q Classes have 0 or more instance variables o Also called fields o Keep state of object May be primitive type o E. g. int, double May be reference type (object) o E. g. , String, Counter, (an array), . . . If public can: o Access or alter reference variables using dot operator Counter c = new Counter(); System. out. println(c. count + ” = ” + c. get. Count()); Comp. Sci 100 E J 1. 9
Java Basics v Variables Modifiers: scope q q v public o Anyone can access protected o Only subclass or same package may access private o Only methods of same class may access (omitted) default o Anyone in same package may access Other Variable Modifiers q q static o Associated with whole class, shared among instances final o Must be initialized, then not changed: CONSTANT Comp. Sci 100 E J 1. 10
Java Basics - Methods v Methods q q q q Like functions, procedure, subroutines, . . . Has header and body Syntax: modifiers type name(parameter_declarations){ method_body } Modifiers like those of variables: o public, private, protected, static, final Type is return type and give type of information being passed back Name is any valid Java identifier name Parameters define type of info being passed into method Comp. Sci 100 E J 1. 11
Java Basics - Methods v Method modifiers q public: anyone can invoke (call) protected: only called from subclass of same package private: only called from same class q (omitted) (default): only called from same package q abstract: has no code (dealt with in subclass) final: cannot be overridden in subclass static: associated with class, not with instance q q v Return types q Use void is no information to be returned (procedure) q Use actual type of information to be returned (function) o requires return statement(s) o only one item returned (may be compound object, e. g. , array) Comp. Sci 100 E J 1. 12
Java Basics - Methods v Parameters q q v Parameter list may be empty (parentheses still required). Parameter list consists of comma separated pairs of types and parameter names. public void set. Age(String name, int age){…} Constructors Used to initialize new objects q Has same name as class and no return type public Counter() { count = 0; } public Professor(String a. Name, String a. Dept){ name = a. Name; department = a. Dept; } q Comp. Sci 100 E J 1. 13
Java Basics v Using a Constructor q Invoked using a new operator o Examples: Professor comp. Sci. Prof = new Professor(”Jeff Chase”, ”Computer Science”); Counter tally = new Counter(); q q Class may have multiple constructors as long a signatures are different If class has no constructors defined, then a default constructor is used that does not initialize anything Comp. Sci 100 E J 1. 14
Java Basics - Methods v The main Method q Required for an Application o This is a stand-alone Java program o Typically invoked from a command line o Must include the following code: public static void main(String[] args){ // main body of the main method } o (The parameter name args can actually be any name you choose. ) o Argument may be used to pass command line arguments to the program. Comp. Sci 100 E J 1. 15
Java Basics - Methods v Blocks and Local Variables Body of a method is a block: a sequence of statements and declarations enclosed in braces ( { }); o Blocks may have blocks nested inside o Variables declared with a block are known only in that block o These variables care called local variables o (We say their scope is limited to that block. ) o (Method parameters are also local to that method. ) o Examples: q public static int sum. Three(int a, int b, int c){ int sum; int partsum = a + b; sum = partsum + c; return sum; } o a, b, sum, and partsum are all local to that method Comp. Sci 100 E J 1. 16
Java Basics - Expressions v Literals q q A literal is a constant value also called a self-defining term Possibilities: o Object: null, the only object literal available o Boolean: true or false o Integer: e. g. , 127, -13, 42, or 0 create 32 -bit integers § For 64 -bit long append L or l, e. g. , 17 L o Floating Point: 3. 14592 or 0. 0 or 2. 1 E 16 for 64 -bit doubles § For 32 -bit float append F or f, e. g. , 2. 56 F or 0. 5 e-12 f o Character: e. g. , ’A’, ’Z’, ’w’, ’$’, ’%’ for 16 bit Unicode § control: ’n’, ’b’, ’f’, ’t’, ’r’ § escape: ’’’, ’\’, ’”’ o Strings: e. g. , ”How are things? ” or ”” (null string) § Use mostly same control and escape characters as char Comp. Sci 100 E J 1. 17
Java Basics - Expressions v Operators q q q Arithmetic o +, -, *, /, % (remainder or mod) Increment/Decrement o e. g. , k++, k-- , ++k, --k Logical (results in boolean value) o <, <=, ==, !=, > o Used only for numbers except == and != o For boolean only: !, &&, || String Concatenation o “I’m “ + 19 + “ years old and live in “ + city Assignment o variable = expression o variable op= expression o ( shorthand for: variable = variable op expression ) Comp. Sci 100 E J 1. 18
Java Basics - Expressions v Operator Precedence Determines order of operation q See table in text q For arithmetic, matches grammar school learning o multiplication and division before addition and subtraction o what is the value of 4. 0 + 5. 0 / 9. 0 * 27. 0 ? o (what is the value for the integer version? ) q Parentheses override precedence rules (and don’t do harm when not needed) q For equal precedence (e. g. , * and /) work strictly left to right except for assignment and prefix operations which work right to left q Precedence rules same as for C and C++ q Comp. Sci 100 E J 1. 19
Java Basics - Expressions v Casting Allows us to change the type of the value of an expression q (Type change must be reasonable and supported. ) q Simple example: double x = 5. 5, y = 2. 9999; int k = (int) x; int m = (int) y; double z = (double) k; // what is in x, y, z, k, m ? q v Implicit Casting q q When an int expression is assigned to a double, casting is automatic (no information is lost). o (double cast at end of previous example not needed) When double is on one side of an operator and int at other, int is automatically cast to a double before op is used. 5 / 9 * (68 – 32) vs. 5. 0 / 9 * (68 – 32) Comp. Sci 100 E J 1. 20
Java Basics - Expressions v Autoboxing/Unboxing Since Java 5. 0, there is automatic casting between primitive types and their related Object types (also called wrapper classes). q Simple examples: Double d = 2. 9; q used to require: Double d = new Double(2. 9); and double x = d; used to require double x = d. double. Value(); Comp. Sci 100 E J 1. 21
Some Java / Matlab Differences v v Compile & Execute vs Interactive q In Java, compile, then run (execute) – like. m files q Matlab executes as you type in program Java requires declaration of variables q q v Need to tell about the variable before creating Declaration is distinct from Definition (creation) Java is not matrix oriented q Operators (+, -, *, /, %), do not work on matrices q You must write code with loops for matrix operations - or use functions (methods) q Comp. Sci 100 E J 1. 22
Some Java / Matlab Differences v No exponentiation operator q q v Syntax differences q Use of braces, {. . . q Semicolon has somewhat different meaning Use quotes, ”. . . ”, for strings not ’. . . ’ Loops and if require parentheses (. . . ) q q v Cannot say X^3 for X 3 Use X*X*X or a function }, in place of xxx … end You’ll find many more differences q Will be an annoying, but transient problem Comp. Sci 100 E J 1. 23
Some Java Vocabulary and Concepts v Java has a huge standard library q q v Java methods have different kinds of access inter/intra class q q q v Organized in packages: java. lang, java. util, javax. swing, … API browseable online, but Eclipse IDE helps a lot Public methods … Private methods … Protected and Package methods … Primitive types (int, char, double, boolean) are not objects but everything else is literally an instance of class Object q foo. call. Me(); Comp. Sci 100 E J 1. 24
Basic data structures and algorithms v Arrays are typed and fixed in size when created q q q v Array. List (and related class Vector and interface List) grows q q q v Not like vector in C++ Don't have to fill the array, but cannot expand it Can store int, double, String, Foo, … Stores objects, not primitives Accessing elements can require a downcast Array. List objects grow themselves intelligently java. util package has lots of data structures and algorithms q Use rather than re-implement, but know how do to do both Comp. Sci 100 E J 1. 25
Tracking different/unique words v We want to know how many times ‘the’ occurs q v Do search engines do this? Does the number of occurrences of “basketball” on a page raise the priority of a webpage in some search engines? o Downside of this approach for search engines? Constraints on solving this problem q q q We must read every word in the file (or web page) Search for the word? Avoid counting twice? Store? Are there fundamental limits on any of these operations? Where should we look for data structure and algorithmic improvements? Comp. Sci 100 E J 1. 26
What does it try to do? Why is it wrong? public class Slow. Unique. Counter implements Unique. Counter{ } public int unique. Count(String[] list) { int count = 0; int diff. Size = list. length; for(int k=0; k < diff. Size; k++){ String word = list[k]; count++; for(int j=k+1; j < diff. Size; j++){ if (list[j]. equals(word)){ list[j] = list[diff. Size-1]; diff. Size--; } } } return count; } Comp. Sci 100 E J 1. 27
Search: measuring performance v How fast is fast enough? /** pre: a contains a. size() entries * post: return true if and only if key found in a */ boolean search(Array. List a, String key) { for(int k=0; k < a. size(); k++) if (a[k]. equals(key)) return true; return false; } v v Java details: parameters? Return values? Array. Lists? How do we measure performance of code? Of algorithm? q Does processor make a difference? G 5? Itanium? 64 -bit? Comp. Sci 100 E J 1. 28
Tradeoffs in processing and counting v Read words, then sort, determine # unique words? q v If we look up words one-at-a-time and bump counter if we haven't seen a word, is this slower than previous idea? q v frog, rat, tiger, tiger How do we look up word, how do we add word Are there kinds of data that make one approach preferable? q What is best case, worst case, average case? Comp. Sci 100 E J 1. 29
Benefits of inheritance, interfaces v Consider new algorithm for determining unique word count public static void test(Unique. Counter uc, String[] list){ double start = System. current. Time. Millis(); int count = uc. unique. Count(list); double end = System. current. Time. Millis(); System. out. println(count+" unique words"); System. out. println((end-start)/1000+" seconds"); } v Why can we pass different kinds of objects to test? q q Why is this an advantage? Inheritance and late/dynamic binding Comp. Sci 100 E J 1. 30
Why inheritance? v shape Add new shapes easily without changing much code q q mammal v Score. Entry q v don’t commit to something concrete until as late as possible Comp. Sci 100 E q v interface or abstraction Function called at runtime concrete subclass q User’s eye view: think and program with abstractions, realize different, but conforming implementations, s 1 = new Circle(); s 2 = new Square(); Interface/abstract base class: q Full. House, Large. Straight Shape All abstract functions implemented Later we'll override “is-a” view of inheritance q Substitutable for, usable in all cases as-a J 1. 31
Example of inheritance v What is behavior of a shape? void do. Shape(Shape s) { System. out. println(s. area()); System. out. println(s. perimeter()); s. expand(2. 0); System. out. println(s. area()); System. out. println(s. perimeter()); } Shape s 1 = new Circle(2); Shape s 2 = new Square(4); Shape s 3 = new Rectangle(2, 5); do. Shape(s 1); do. Shape(s 2); do. Shape(s 3); Comp. Sci 100 E J 1. 32
Inheritance (language independent) v First view: exploit common interfaces in programming q q v Second view: share code, factor code into parent class q q v Iterators in Java or C++/Tapestry Implementation varies while interface stays the same Code in parent class shared by subclasses Subclasses can override inherited method o Subclasses can override and call Polymorphism/late(runtime) binding (compare: static) q Function actually called determined when program runs, not when program is compiled Comp. Sci 100 E J 1. 33
Who is Alan Perlis? v v v It is easier to write an incorrect program than to understand a correct one Simplicity does not precede complexity, but follows it If you have a procedure with ten parameters you probably missed some If a listener nods his head when you're explaining your program, wake him up Programming is an unnatural act Won first Turing award http: //www. cs. yale. edu/homes/perlis-alan/quotes. html Comp. Sci 100 E J 1. 34
- Slides: 34