Java Basics (ala Goodrich & Tamassia)Java BasicsSlide 3Slide 4Slide 5Slide 6Slide 7Slide 8Slide 9Slide 10Java Basics - MethodsSlide 12Slide 13Slide 14Slide 15Slide 16Java Basics - ExpressionsSlide 18Slide 19Slide 20Slide 21Java Basics – Control of FlowJava Basics – Control FlowSlide 24Java Basics – LoopsSlide 26Slide 27Slide 28Slide 29Slide 30CompSci 100EJB1.1Java Basics (ala Goodrich & Tamassia)Everything is in a class A minimal program:public class Hello { public static void main(String[] args) { System.out.println(”Hello Computer Science”); }}Output? Where? Do colors mean something?Identify the pieces . . .CompSci 100EJB1.2Java BasicsObjects Every object is an instance of a class (which defines its type)Objects contain data (state) and function (methods)StateStored in instance variables (fields, members)Can be base types (e.g. integers) or instances of (objects) of other classesFunctionExpressed as methods (subroutines, functions, procedures…)These define the behavior of objects of this classCompSci 100EJB1.3Java BasicsDeclaring a Class: public class Counter { protected int count; Counter() { count = 0; } public int getCount() { return count; } public void incCount() { count = count + 1; } public void decCount() { count = count – 1; }} Identify the methods by kind Constructor Accessor Mutator (modifier) Note Syntax from this and previous examples Braces Semicolons Parentheses Indentifiers . . .CompSci 100EJB1.4Java BasicsClass ModifiersAbstract, final, public, default Reserved WordsMay not be used as identifiersShown in red by Eclipse and many of our examplesSee table in text (p4) or in any Java textCommentsFor human consumption: ignored by compilerInline comments: //oEffective for rest (to end) of current lineBlock comments: /* */oEffective between start and stop groupsCompSci 100EJB1.5Java BasicsPrimitive Types (base types)Built-in data types; native to most hardwareNote: not objects (will use mostly first four)boolean (1bit)int (4 bytes)double (8 bytes)char (2 bytes)Constants/Literals (by example):boolean f = false;int i = 32769;double d = 0.333333;char c = ’x’;byte (1 byte = 8 bits)short (2 bytes)long (8 bytes)float (4 bytes)byte b = 33;short s = 21;long l = 289L;float = 3.141592F;CompSci 100EJB1.6Java BasicsCreating 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.getCount() + ” d = ” + d.getCount()); c.incCount(); d.decCount(); System.out.println(”c = ” + c.getCount() + ” d = ” + d.getCount()); d = c; // what does this really mean??? c.incCount(); d.incCount(); System.out.println(”c = ” + c.getCount() + ” d = ” + d.getCount()); }}CompSci 100EJB1.7Java BasicsString Objectsstring is a sequences of characters (char)oUnicode (16 bit)String is a built-in classoConstants: ”this is an example”String Concatenation (+) String s = ”Happy birthday to you.”; s = s + ”\n” + s; System.out.println(s); // what ?CompSci 100EJB1.8Java BasicsObject ReferencesWhen creating object with new, get location or address of new objectTypically assign this to a reference variable: Counter c = new Counter();Every object reference variable refers to object or nullNull is an important value that indicates object not created or not available.Can have multiple references to same objectAccess members of class using dot operator (“.”). Counter c = new Counter(); c.incCount();May have multiple methods with same name but different signature: e.g.: c.incCount(); c.incCount(5);CompSci 100EJB1.9Java BasicsInstance VariablesClasses have 0 or more instance variablesoAlso called fieldsoKeep state of objectMay be primitive typeoE.g. int, doubleMay be reference type (object)oE.g., String, Counter, (an array), . . .If public can:oAccess or alter reference variables using dot operator Counter c = new Counter(); System.out.println(c.count + ” = ” + c.getCount());CompSci 100EJB1.10Java BasicsVariables Modifiers: scopepublicoAnyone can accessprotectedoOnly subclass or same package may accessprivateoOnly methods of same class may access(omitted) defaultoAnyone in same package may accessOther Variable ModifiersstaticoAssociated with whole class, shared among instancesfinaloMust be initialized, then not changed: CONSTANTCompSci 100EJB1.11Java Basics - MethodsMethodsLike functions, procedure, subroutines, . . .Has header and bodySyntax: modifiers type name(parameter_declarations){ method_body }Modifiers like those of variables:opublic, private, protected, static, finalType is return type and give type of information being passed backName is any valid Java identifier nameParameters define type of info being passed into methodCompSci 100EJB1.12Java Basics - MethodsMethod modifierspublic: anyone can invoke (call)protected: only called from subclass of same packageprivate: only called from same class(omitted) (default): only called from same package abstract: has no code (dealt with in subclass)final: cannot be overridden in subclassstatic: associated with class, not with instanceReturn typesUse void is no information to be returned (procedure)Use actual type of information to be returned (function)orequires return statement(s)oonly one item returned (may be compound object, e.g., array)CompSci 100EJB1.13Java Basics - MethodsParametersParameter list may be empty (parentheses still required).Parameter list consists of comma separated pairs of types and parameter names.public void setAge(String name, int age){…}ConstructorsUsed to initialize new objectsHas same name as class and no return typepublic Counter() {count = 0;}public Professor(String aName, String aDept){ name = aName; department = aDept;}CompSci 100EJB1.14Java BasicsUsing a ConstructorInvoked using a new operatoroExamples:Professor compSciProf = new Professor(”Jeff Chase”, ”Computer Science”);Counter tally = new Counter();Class may have multiple constructors as long a
View Full Document