SOFTWARE AND PROGRAMMING 1 Lecture MB 33 7

SOFTWARE AND PROGRAMMING 1 Lecture: MB 33 7: 30 -9: 00 (except 11&18. 01. 06) Lab: B 43, MB 321, MB 536 6: 00 -7: 30 (from 25. 01. 05) [each student must have obtained access to Birkbeck computing] SORRY; Rooms and allocations are wrong here; please consult first slide in Lecture 3!- B. M. 25/1/6 Lab MB 321: students whose family names fall in A-D Instructor: Mrs Jenny Hu SCSIS, room NG 26, tel. 020 7631 6726 E-mail: jennychhu@yahoo. com Lab MB 536: students whose family names fall in E-L Instructor: Mr Zheng Zhu LKL, tel. 020 7763 2115 E-mail: zheng@dcs. bbk. ac. uk Lab B 43: students whose family names fall in M-Y Instructor: Prof. Boris Mirkin SCSIS, room 111, tel. 020 7631 6746 E-mail: mirkin@dcs. bbk. ac. uk

SOFTWARE AND PROGRAMMING 1 Web. CT/Tests/Assignments: Marie-Helene Ng SCSIS, room NG 26, tel. 0207 631 6550 E-mail: marie-helene@dcs. bbk. ac. uk To be able to submit your assignments you must have sent your CCS username to Marie-Helene by 31 January

Webpages The course web page is at webct. bbk. ac. uk Please check it regularly. It will be used for announcements and assignments. Another page, at an open-to-all web-site, will function with relevant materials too: www. dcs. bbk. ac. uk/~mirkin/sp 105 3

Formerly Recommended Texts 1. David J. Barnes & Michael Kölling Objects First with Java: A Practical Introduction using Blue. J, Second edition, Pearson Education, 2005, ISBN 0 -13 -124933 -9 The publisher supplies a helpline (team’s telephone included) in installing the related software 2. J. Farrell Java Programming, Second edition, Course Technology, Thompson, 2003, ISBN 0 -619 -21500 -3 3. I. Pohl, C. Mc. Dowell Java by dissection, Addison-Wesley, 2000, ISBN 0201751585 4. Free: ON-LINE text by D. Eck (on my web site) and other useful URLs 4

New Recommended Text Q. Charatan, A. Kans Java in Two Semesters, Second edition, The Mc. Grow-Hill Education, 2006, ISBN 978 -0 -07 -710889 -2 [ Free: ON-LINE text by D. Eck (on my web site) and other useful URLs] 5

Software is free • Available on BBK’s network – Java JDK (which allows you to compile and execute your program) – Blue. J (Preferred editor) • Installing Blue. J (for home use) – First download the Java JDK from http: //java. sun. com/j 2 se/1. 5. 0/download. jsp – Download Blue. J from http: //www. bluej. org/download. html – Run “bluejsetup-202. exe” and follow the given instructions 6

Concepts from lecture 1 • Compiler (javac. exe) and Interpreter (java. exe) • Class (template) and Object (its instantiation); every Java program must be a class • Variable and its type; primitive types • Method (input-output operation) and its Parameters (inputs - with their types at method’s description) 7

Concepts to be learnt • Arithmetic expression and precedence • Boolean expression • Statement (a Java instruction) • Loop for • Usage in classes for hello-printing and ticket-vending machine (Blue. J) 8

Objects and classes • Classes: program templates – represent all objects of a kind (example: “student”) • Objects = instances – A template copy to represent a specific element of the class (“an individual student”) – Instances are created with the so-called constructors, explicit in JDK or somewhat easier in Blue. J 9

Basic class structure public class Ticket. Machine { Inner part of the class omitted. } public class Class. Name { Variables Constructors Methods } The outer wrapper of Ticket. Machine The contents of a class 10

Method in Java is a named set of instructions that transforms some input into an output. This is, actually, a machine implementation of the concept of algorithm which itself is a computational analogue to the mathematical concept of function. Static method: is shared by all instances. 11

Structure of a method Output’s type Inputs modifiers return-type name ( parameter-list ) { statements; return variable/expression; //if return type is not void } Modifiers: – static method/variable that belongs to class as whole and is shared by all – public - method/variable that is accessible from anywhere – private - method/variable that is accessible from 12 only within the class

Fields • Fields store values for an object. • They are also known as instance variables. • Use the Inspect option to view an object’s fields. • Fields define the state of an object. public class Ticket. Machine { private int price; private int balance; private int total; Constructor and methods omitted. } visibility modifier type variable name private int price; 13

Assigning values • Values are stored into fields (and other variables) via assignment statements: – variable = expression; – price = ticket. Cost; • The value on the right is assigned to a variable on the left. • A variable stores a single value, so any previous value is lost. 14

Variable • It provides for multiple uses of the same program • A variable is a name for a location in memory that can hold data. • Variables are declared and initialised • A variable declaration includes the following: – A data type that identifies the type of data that is stored in the variable – An identifier that is the variable’s name – An optional assigned initial value – Semicolon. 15

Scope of a variable: The range of statements that can access the variable. It stretches from the declaration point to the end of the block containing the declaration Q: WHAT is BLOCK ? Q: WHAT is DECLARATION? (part within curly braces{…} ) (type name ; 3 -part command) 16

Two JAVA environments • Java Developer Kit JDK (currently, J 2 SE) (Conventional) • Blue J (A public project to make JAVA coding easier) – Both available in Birkbeck 17

Conventional JDK: Editing • A source code can be edited in any text editor: Notepad, emacs, PFE, . . . • MS Word caveat: by default, Word does not save in ASCII text format • Make sure to save the code before compiling! The file name: the same as that of the class, with extension: say, class Nic. Te{…} must be saved as file Nic. Te. java, case sensitive 18

Command line invocation • compilation and execution of Java in JDK are done from a command line • On Microsoft systems: DOS shell • On Unix: Unix shell • Must make sure that the commands for compiler and runtime (JVM) are in the command path. 19

Compiling with JDK • Name of the JDK compiler: javac • To invoke: javac <source name> • compiles <source name> and all classes it depends on into an executable on JVM file <source name>. class • Example: javac Nic. Te. java produces file Nic. Te. class 20

Execution • “java” starts the Java virtual machine: java Nic. Te • The named class is loaded and execution is started. • Other classes are loaded as needed. • Only possible if class has been compiled into a file, say, Nic. Te. class 21

JDK Problem: Execute what? How does the system know which method to execute? 22

The main method in JDK • The JDK java system always executes a method called main with a certain signature: Signature ____________ public static void main(String[] args) {. . . } • To work with JDK, such a method must be present in your program! 23

A simplest program /* Hello. World. java Purpose: printing a message to the screen */ class HW { // Each program is organised as a class public static void main(String[] args) { System. out. println("Hello, World!"); } } // end of class HW /* • • • Always Three Types of Elements ONLY: comments class (with modifiers) methods (with modifiers and parameters) */ 24

Blue. J coding • Blue. J programs are organised in the so-called projects • A Blue. J project is stored in a directory on disk • Some files store the source code, some store the compiled code, some store additional information. 25

The Blue. J directory structure project: calculator Calculator User. Interface Calc. Engine c: bluejcalculator bluej. pkg bluej. pkh Calculator. java Calculator. class Calculator. ctxt User. Interface. java User. Interface. class User. Interface. ctxt Calc. Engine. java Calc. Engine. class Calc. Engine. ctxt 26

The Blue. J file structure • bluej. pkg - the package file. Contains information about classes in the package. One per package. • bluej. pkh - backup of the package file. • *. java - standard Java source file (text). One per class. • *. class - standard Java code file. One per class • *. ctxt - Blue. J context file. Contains extra information for a class. One per class. 27

Blue. J Hello. World N times public class Hello. N { int number; \ variable declared public void go() { System. out. println("Hello, world"); } public Hello. N(int howmany) {number=howmany; } \constr-r to initialise an object public void prrt() \printing number times { for(int i=1; i<=number; i++) \loop go(); System. out. println("ok"); } 28

Loop for(int var=1; var<=st; var++){do operation depending on var} var++ is not var=var+2; • Two types of parentheses: () and {} • The expression in () consists of three different items: initialising a counting variable, variable update, and stop-condition • Given a value of var, stop-condition is checked; if true, {} is executed, after which var is updated; if no, the program proceeds further on, after the block { } 29

No { } in for-loop in Hello. N Why? Let us add { }: where? Is there any difference between before and after “ok”? 30

Arithmetic Operations in Java • * 5 3=15 • / 36/9=4, 39/50=0 (integers) • / 36. 0/9=4. 0, 39. 0/9=4. 3333, 39. 0/50=0. 78 (reals) • % 36%9=0, 39%9=3, 39%50=39 • + 5+3=8 • 5– 3=2 • Other operators such as Abs or exp or log are in class Math of Java (to be explained later) 31

Arithmetic expressions • 2*6/4+5– 2*3= 3+5– 6=2 (integers) • 2 * 6. 0 / (4 + 5) – 2 * 3 = 12. 0/9 – 6 = – 4. 67 (reals are here) • 2 * 6 / 4 + (5 – 2) * 3 = 12 32

Ticket Machine (1) /* * Ticket. Machine models a ticket machine that issues * flat-fare tickets. */ public class Ticket. Machine{ private int price; private int balance; private int total; public Ticket. Machine(int ticket. Cost) //constructor { price = ticket. Cost; balance = 0; total = 0; } public int get. Price() { return price; } public int get. Balance() { return balance; } // see next page for continuation 33

Ticket Machine (2) // Ticket. Machine’s continuation public void insert. Money(int amount) { if(amount > 0) balance = balance + amount; else { System. out. println("Use a positive amount: " + amount); } } public int refund. Balance() { int amount. To. Refund; amount. To. Refund = balance; balance = 0; return amount. To. Refund; } // continued on the next page 34

Ticket Machine (3) // Ticket. Machine’s end public void print. Ticket() { if(balance >= price) { // Simulate the printing of a ticket. System. out. println("#########"); System. out. println("# The Blue. J Line"); System. out. println("# Ticket"); System. out. println("# " + price + " pence. "); System. out. println("#########"); System. out. println(); total = total + price; // Update the total balance = balance - price; // Update the balance } else { System. out. println("You must insert at least: " + (price - balance) + " more pence. "); } } }//end of class 35

Questions • How many methods are in Ticket. Machine? • If there is any syntactic difference between a method and constructor? • Which of the methods are accessors and which are mutators? 36

Accessor methods • Accessors provide information about the state of an object. • Methods have a structure consisting of a header and a body. • The header defines the method’s signature. public int get. Price() • The body encloses the method’s statements. 37

Accessor methods return type visibility modifier method name parameter list (empty) get. Price() public int { return price; } return statement start and end of method body (block) 38

Mutator methods • Have a similar method structure: header and body. • Used to mutate (i. e. change) an object’s state. • Achieved through changing the value of one or more fields. – Typically contain assignment statements. – Typically receive parameters. 39

Mutator methods visibility modifier return type (void) method name parameter public void insert. Money(int amount) { balance = balance + amount; } field being changed assignment statement 40

Printing from methods public void print. Ticket() { // Simulate the printing of a ticket. System. out. println("#########"); System. out. println("# The Blue. J Line"); System. out. println("# Ticket"); System. out. println("# " + price + " cents. "); System. out. println("#########"); System. out. println(); // Update the total collected with the balance. total = total + balance; // Clear the balance = 0; } 41

Passing data via parameters 42
- Slides: 42