420 likes | 434 Views
Join Mrs. Jenny Hu for a lecture on software and programming, covering topics such as Java programming, variables, methods, and class structure. The lecture will be held in room MB33 from 7:30-9:00, excluding dates 11 and 18.01.06.
E N D
SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11&18.01.06) Lab: B43, MB321, MB536 6:00-7:30 (from 25.01.05) [each student must have obtained access to Birkbeck computing] Lab MB321: students whose family names fall in A-D Instructor: Mrs Jenny Hu SCSIS, room NG26, tel. 020 7631 6726 E-mail: jennychhu@yahoo.com Lab MB536: 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 B43: 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 WebCT/Tests/Assignments: Marie-Helene Ng SCSIS, room NG26, 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 atwww.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/sp105
Formerly Recommended Texts • David J. Barnes & Michael KöllingObjects First with Java: A Practical Introduction using BlueJ, 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. McDowell • Java by dissection, Addison-Wesley, 2000, ISBN 0201751585 • 4. Free: ON-LINE text by D. Eck (on my web site) and other useful URLs
New Recommended Text Q. Charatan, A. Kans Java in Two Semesters, Second edition, The McGrow-Hill Education, 2006, ISBN 978-0-07-710889-2 [ Free: ON-LINE text by D. Eck (on my web site) and other useful URLs]
Software is free • Available on BBK’s network • Java JDK (which allows you to compile and execute your program) • BlueJ (Preferred editor) • Installing BlueJ (for home use) • First download the Java JDK from http://java.sun.com/j2se/1.5.0/download.jsp • Download BlueJ from http://www.bluej.org/download/download.html • Run “bluejsetup-202.exe” and follow the given instructions
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)
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 (BlueJ)
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 BlueJ
Basic class structure The outer wrapper of TicketMachine public class TicketMachine { Inner part of the class omitted. } public class ClassName { Variables Constructors Methods } The contents of a class
Method 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.
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 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 TicketMachine { private int price; private int balance; private int total; Constructor and methods omitted. } visibility modifier type variable name private int price;
Assigning values • Values are stored into fields (and other variables) via assignment statements: • variable = expression; • price = ticketCost; • 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.
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 initialisedA 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
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 ? (part within curly braces{…} ) Q: WHAT is DECLARATION? (type name ; 3-part command)
Java Developer Kit JDK (currently, J2SE) (Conventional) Blue J (A public project to make JAVA coding easier) Both available in Birkbeck Two JAVA environments
A source code can be edited in any text editor: Notepad, emacs, PFE, ... MS Wordcaveat: 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 NicTe{…} must be saved as file NicTe.java, case sensitive Conventional JDK: Editing
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. Command line invocation
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 NicTe.java produces file NicTe.class Compiling with JDK
“java” starts the Java virtual machine: java NicTe 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, NicTe.class Execution
How does the system know which method to execute? JDK Problem: Execute what?
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! The main method in JDK
A simplest program /* HelloWorld.java Purpose: printing a message to the screen */ class HelloWorld { // Each program is organised as a class public static void main(String[] args) { System.out.println("Hello World!"); } } // end of class HelloWorld /* Always Three Types of Elements ONLY: • comments • class (with modifiers) • methods (with modifiers and parameters) */
BlueJ coding • BlueJ programs are organised in the so-called projects • A BlueJ project is stored in a directory on disk • Some files store the source code, some store the compiled code, some store additional information.
The BlueJ directory structure c:\bluej\calculator\ project: calculator bluej.pkg bluej.pkh Calculator.java Calculator.class Calculator.ctxt UserInterface.java UserInterface.class UserInterface.ctxt CalcEngine.java CalcEngine.class CalcEngine.ctxt Calculator UserInterface CalcEngine
The BlueJ 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 - BlueJ context file. Contains extra information for a class. One per class.
BlueJ HelloWorld N times public class HelloN { int number; \\ variable declared public void go() { System.out.println("Hello, world"); } public HelloN(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"); } }
Loop for for(int var=1;var<=st;var++){do operation depending on var} • Two types of parentheses: () and {} • The expression in () consists of three different items: initialising a variable,variable update, and stop-condition • Given a value of var, {} is executed, after which varis updated, then stop-condition checked and, if yes, {} is executed again; if no, the program proceeds further on
No { } in for-loop in HelloN Why? Let us add { }: where? Is there any difference between before and after “ok”?
Arithmetic Operations in Java • * 53=15 • / 36/9=4, 39/9=4, 39/50=0 (integers) • / 36.0/9=4.0, 39.0/9=4.33333333, 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)
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
Ticket Machine (1) /* * TicketMachine models a ticket machine that issues * flat-fare tickets. */ public class TicketMachine{ private int price; private int balance; private int total; public TicketMachine(int ticketCost) //constructor { price = ticketCost; balance = 0; total = 0; } public int getPrice() { return price; } public int getBalance() { return balance; } // see next page for continuation
Ticket Machine (2) // TicketMachine’s continuation public void insertMoney(int amount) { if(amount > 0) balance = balance + amount; else { System.out.println("Use a positive amount: " + amount); } } public int refundBalance() { int amountToRefund; amountToRefund = balance; balance = 0; return amountToRefund; } // continued on the next page
Ticket Machine (3) // TicketMachine’s end public void printTicket() { if(balance >= price) { // Simulate the printing of a ticket. System.out.println("##################"); System.out.println("# The BlueJ 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
Questions • How many methods are in TicketMachine? • If there is any syntactic difference between a method and constructor? • Which of the methods are accessors and which are mutators?
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 getPrice() • The body encloses the method’s statements.
Accessor methods return type visibility modifier method name parameter list (empty) public int getPrice() { return price; } return statement start and end of method body (block)
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.
Mutator methods return type (void) visibility modifier method name parameter public void insertMoney(int amount) { balance = balance + amount; } field being changed assignment statement
Printing from methods public void printTicket() { // Simulate the printing of a ticket. System.out.println("##################"); System.out.println("# The BlueJ 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. balance = 0; }