1 計算機程式設計 ( 下 ) February 2002 陳正佳. 2 Course Information l 上課內容 : Java and Object-Orient Programming l 時間 : 13:10~16:00, Friday. l 地點 : 應數系 PC 教室 l TextBook:

Slides:



Advertisements
Similar presentations
CSCE 145: Algorithmic Design I Chapter 1 Intro to Computers and Java Muhammad Nazmus Sakib.
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction.
Introduction to Computers and Java Module 1. Objectives overview computer hardware and software introduce program design and object-oriented programming.
Slides prepared by Rose Williams, Binghamton University Chapter 1 Getting Started 1.1 Introduction to Java.
Introduction to Computers and Java Objects
Copyright © 2012 Pearson Education, Inc. Chapter 1: Introduction to Computers and Programming.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 1 “ Introduction to Java and OOP”
ICS 102 Computer Programming University of Hail College of Computer Science & Engineering Computer Science and Software Engineering Department.
Introduction Algorithms and Programming. Computer Programming  A form of problem solving  Or, more accurately, a way to solve problems  What we will.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 1 Introduction.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 INTRODUCTION TO OOP Objective: Know the difference between functional programming and OOP Know basic terminology in OOP Know the importance of OOP Know.
1 INTRODUCTION TO OOP Objective: Know the difference between functional programming and OOP Know basic terminology in OOP Know the importance of OOP Know.
1 I.Introduction to Algorithm and Programming Algoritma dan Pemrograman – Teknik Informatika UK Petra 2009.
CSC 110 Introduction to Computer Science for Majors Summer 2009 Introduction to Computers and Java 1.
CS102 Introduction to Computer Programming
Computer Programming-1 CSC 111 Chapter 1 : Introduction.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 1 Introduction to Computers and Programming.
Chapter Introduction to Computers and Programming 1.
CSC 125 Introduction to C++ Programming Chapter 1 Introduction to Computers and Programming.
Lecturer: Dr. AJ Bieszczad Chapter 1 COMP 150: Introduction to Object-Oriented Programming 1-1 l Background information »important regardless of programming.
Chapter 1Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 1 l Background information »important regardless of programming.
O BJECT O RIENTATION F UNDAMENTALS Prepared by: Gunjan Chhabra.
©Silberschatz, Korth and Sudarshan1.1 Chapter 1: Introduction to Computers and Java Objects Background information  hardware  software  computer languages.
COMP 110 Spring Announcements Computers in class on Friday: Lab Office Hours: Monday 12-2 New students see me after class Administrative Changes.
COMP 110: Introduction to Programming Tyler Johnson January 14, 2009 MWF 11:00AM-12:15PM Sitterson 014.
An intro to programming. The purpose of writing a program is to solve a problem or take advantage of an opportunity Consists of multiple steps:  Understanding.
Copyright © 2012 Pearson Education, Inc. Chapter 1: Introduction to Computers and Programming.
Chapter 1: Introduction to Computers and Programming.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 1: Introduction to Computers and Programming.
111 © 2002, Cisco Systems, Inc. All rights reserved.
1 Computing Software. Programming Style Programs that are not documented internally, while they may do what is requested, can be difficult to understand.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
What is a Computer? An, electrical machine, that can be programmed to accept data (input), process it into useful information (output) and store it away.
Chapter 1 What is Programming? Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
Introduction to Computers and Java Chapter 1.3. A Sip of Java: Outline History of the Java Language Applets A First Java Program Compiling a Java Program.
Chapter 1Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Java Byte Code l The Java compiler generates Java Byte Code. (Most.
Introduction to Computer Systems and the Java Programming Language.
Java Programming, Second Edition Chapter One Creating Your First Java Program.
Chapter 1Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 1 l Background information »important regardless of programming.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
CHAPTER 3 GC Java Fundamentals. 2 BASICS OF JAVA ENVIRONMENT  The environment  The language  Java applications programming Interface API  Various.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 1- 1 October 20, October 20, 2015October 20, 2015October 20,
Chapter 1 Section 1.1 Introduction to Java Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Introduction to Computers and Java Module 1. Objectives overview computer hardware and software introduce program design and object-oriented programming.
Lecture 1 Introduction Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Mrs. Ulshafer August, 2013 Java Programming Chapter 1.
FIRST JAVA PROGRAM. JAVA PROGRAMS Every program may consist of 1 or more classes. Syntax of a class: Each class can contain 1 or more methods. public.
An Object-Oriented Approach to Programming Logic and Design Chapter 1 An Overview of Computers and Logic.
Chapter 1- Basic Computing and your first program.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 1 Introduction to Computers and Programming.
Computer and Programming. Computer Basics: Outline Hardware and Memory Programs Programming Languages and Compilers.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
Lesson 1 1 LESSON 1 l Background information l Introduction to Java Introduction and a Taste of Java.
Brief Version of Starting Out with C++ Chapter 1 Introduction to Computers and Programming.
1 Types of Programming Language (1) Three types of programming languages 1.Machine languages Strings of numbers giving machine specific instructions Example:
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 1: Introduction to Computers and Programming.
Java Programming Fifth Edition Chapter 1 Creating Your First Java Classes.
Chapter 1Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 1 l Background information »important regardless of programming.
Chapter 1: Introduction to Computers and Programming
Lecture 1: Introduction to JAVA
Introduction to Computers and Java
Data types and variables
Java programming lecture one
INTRODUCTION TO OOP Objective:
Computers: Hardware and Software
Introduction to Java Brief history of Java Sample Java Program
Computer Programming-1 CSC 111
Presentation transcript:

1 計算機程式設計 ( 下 ) February 2002 陳正佳

2 Course Information l 上課內容 : Java and Object-Orient Programming l 時間 : 13:10~16:00, Friday. l 地點 : 應數系 PC 教室 l TextBook: Java: An Introduction to Computer Science & Programming, 2/e, by Walter Savitch, Prentice Hall, ( 開發代理 ) l course page: l Java 線上參考網頁 : »The Java Tutorial From Sun »Java 2 SDK Documentation »The Java Language Specification »

3 Course Information (continued) l 評分方式 : »4~5 Programming Exercises (40 %) »MidTerm Examination (25%) »Final Examination (25%) »Class Participation (10%) l 先修課程 : »C or other high level language programming. »experience of web navigation

4 開發工具 l Java 2 SDK Version 1.4 ( l BeanShell ( l bluej ( l IBM VisualAge for java l Forte For Java(3.0 community edition) l Borland Builder6 Personal, jde,… l Editors: JPad, notepad, ultraedit, editplus 2, textpad,… (find the locations of these tools yourself by search engine)

5 Lecture 1* l Background information »important regardless of programming language l Introduction to Java Introduction to Computers and Java Objects Note*: Lecture content adapted from Savitch’s companion slides

6 Computer Basics l Computer system: hardware + software l Hardware: the physical components l Software: the instructions that tell the hardware what to do

7 Common Hardware Components l Processor (CPU) »Central Processing Unit »Interprets and executes the instructions l Memory »main & auxiliary »holds data and instructions l I nput device(s) »mouse, keyboard, etc. l O utput device(s) »video display, printer, etc. l CPU and memory are physically housed together Standard Hardware Organization Memory (main & auxiliary) Processor (CPU) Input Devices (such as mouse and keyboard) Output Devices (such as video display or printer)

8 Physical Organization l Keyboard l Monitor l Chassis »CPU »memory »disk drives »I/O connectors »etc.

9 Two Kinds of Memory l Main »working area »temporarily stores program and data (while program is executing) l Auxiliary »permanent (more or less) »saves program and results »includes floppy & hard disk drives, CDs, tape, etc.

10 Main Memory Organization l Bit = one binary digit »Binary digit can have only one of two values, 0 or 1 l Byte = 8 bits l “Byte Addressable” »Main memory is a list of numbered locations that contain one byte of data in each location l Number of bytes per data item may vary

11 Auxiliary Memory Organization

12 Running a Program Program Computer Data (input for the program) Output Program—a set of instructions for a computer to follow

13 Many Types of Programs l User-created applications l Existing applications »word-processor/editor »web browser »compiler or assembler »etc. l Operating System »DOS, MS- Windows(3.x, 95, 98, NT), MacOS, UNIX, etc.

14 Various Types of User Interfaces l Command-line »type in key words and letters »DOS and UNIX l Menu( 選單式 ) »parts of DOS and Windows l GUI (Graphical User Interface) »click on icon »also called “event-driven” »MacOS, Windows

15 Programming Language Hierarchy

16 The highs and lows of programming languages... l High-Level Language (HLL) »closest to natural language »words, numbers, and math symbols »not directly understood by hardware »“portable” source code (hardware independent) »Java, C, C++, COBOL, FORTRAN, BASIC, Lisp, Ada, etc. l Machine Language (lowest level) »least natural language for humans, most natural language for hardware »just 0s and 1s »directly understood by hardware »not portable (hardware dependent)

17 Assembly Language (middle level) l a more or less human readable version of machine language l words, abbreviations, letters and numbers replace 0s and 1s l easily translated from human readable to machine executable code l like machine code, not portable (hardware dependent)

18 Getting from Source to Machine Code l “Compiling a program” translating from a high-level language source code to machine (object, or executable) code. l “Compiler” a program that translates HLL source code to machine (object, or executable) code. l “Assembly” translating from assemble language source code to machine (object, or executable) code. l “Assembler” a program that translates assembly source code to machine (object, or executable) code. l Compilers need to know the specific target hardware

19 Compilers vs. Assemblers vs. Interpreters l Compilers and Assemblers »translation is a separate user step »translation is “off-line,” i.e. not at run time l Interpreters - another way to translate source to object code »interpretation (from source to object code) is not a separate user step »translation is “on-line,” i.e. at run time Compiler, Assembler, or Interpreter Source Code Object Code

20 Java Program Translation l Both Compilation and Interpretation l Intermediate Code: “Byte Code” »portable low-level code »similar to assembly code, but hardware independent »invisible to Java programmer l Interpreter translates from generic byte code to hardware-specific machine code Java Program Data for Java Program Java Compiler Byte-Code Program Byte-Code Interpreter Machine-Language Instructions Computer Execution of Machine-Language Instructions Output of Java Program Java Virtual Machine (JVM)

Java Program Data for Java Program Java Compiler Byte-Code Program Byte-Code Interpreter Machine-Language Instructions Computer Execution of Machine-Language Instructions Output of Java Program JVM Linker Previously Compiled Helper Programs Java Program Translation Including Linker

22 Object-Oriented Programming l OOP l A design and programming technique l Some terminology: »object - usually a person, place or thing (a noun) »method - an action performed by an object (a verb) »type or class - a category of similar objects (such as automobiles) l Objects have both data and methods l Objects of the same class have the same data elements and methods l Objects send and receive messages to invoke actions

23 Example of an Object Class Data Items: (properties, attributes) »manufacturer’s name »model name »year made »color »number of doors »size of engine »etc. Methods:(services, behavior) »Define data items (specify manufacturer’s name, model, year, etc.) »Change a data item (color, engine, etc.) »Display data items »Calculate cost »etc. Class: automobile

24 Why OOP? l Save development time (and cost) by reusing code »once an object class is created it can be used in other applications l Easier debugging »classes can be tested independently »reused objects have already been tested

25 Design Principles of OOP Three main design principles of Object- Oriented Programming(OOP): l Encapsulation l Polymorphism l Inheritance

26 Encapsulation l Encapsulation means to design, produce, and describe software so that it can be easily used without knowing the details of how it works. l Also known as data hiding, data abstraction An analogy: l When you drive a car, you don’t have know the details of how many cylinders the engine has or how the gasoline and air are mixed and ignited. l Instead you only have to know how to use the controls.

27 Polymorphism l Polymorphism—the same word or phrase can be mean different things in different contexts l Analogy: in English, bank can mean side of a river or a place to put money In Java, two or more classes could each have a method called output Each output method would do the right thing for the class that it was in. One output might display a number whereas a different one might display a name.

28 Inheritance l Inheritance—a way of organizing classes l Term comes from inheritance of traits like eye color, hair color, and so on. l Classes with properties in common can be grouped so that their common properties are only defined once.

29 An Inheritance Hierarchy Vehicle AutomobileMotorcycleBus SedanSports CarSchool BusLuxury Bus What properties does each vehicle inherit from the types of vehicles above it in the diagram?

30 Algorithms l Algorithm - a set of instructions (steps) for solving a problem. »must be precise »must be complete l May be in a number of different formats »natural language (such as English) »a specific programming language »a diagram, such as a flow chart »pseudocode - a mix of natural and programming language

31 Example of an Algorithm Algorithm that determines the total cost of a list of items: 1. Write the number 0 on the blackboard. 2. Do the following for each item on the list: Add the cost of the item to the number on the blackboard. Replace the old number on the board by this sum. 3. Announce that the answer is the number written on the board

32 Program Design Process l Design, then code l Design process »define the problem clearly »design objects your program needs »develop algorithms for the methods of objects »describe the algorithms, usually in pseudocode »write the code »test the code »fix any errors and retest

33 Types of Errors l Syntax l Run-Time l Logic

34 Syntax Errors l a “grammatical” error l caught by compiler (“compiler-time error”) l automatically found, usually the easiest to fix l cannot run code until all syntax errors are fixed l error message may be misleading Example: Misspelling a command, for example “rturn” instead of “return”

35 Run-Time Errors l An execution error (during run-time) l Not always so easy to fix l Error message may or may not be helpful Example: Division by zero - if your program attempts to divide by zero it automatically terminates and prints an error message.

36 Logic Errors Just because it compiles and runs without getting an error message does not mean the code is correct! l An error in the design (the algorithm) or its implementation »code compiles without errors »no run-time error messages »but incorrect action or data occurs during execution l Generally the most difficult to find and fix l Need to be alert and test thoroughly »think about test cases and predict results before executing the code

37 Logic Error Examples l Algorithm Error: »averageOfFiveScores = SumOfScores/2 (should divide by 5) l Implementation Error: »typed in wrong symbol in source code - sum = a - b; (should be sum = a + b; )

38 Finally! Now, a taste of Java! History l James Gosling, Sun Microsystems, Inc.Originally »originally a language for programming home appliances l later (1994) used for World Wide Web applications (since byte code can be downloaded and run without compiling it) l eventually used as a general-purpose programming language (for the same reason as above plus it is object- oriented) l Why the name “Java”? Not sure - it may just be a name that came during a coffee break and it had not been copyrighted, yet.

39 Applets vs. Java Applications l Applets »Java programs intended to be downloaded via the WWW and run immediately »“little applications” »requires a web browser l Applications »Java programs intended to be installed then run »often larger applications l Slightly different programming for each, but both are easy to do

40 public class FirstProgram { public static void main(String[] args) { System.out.println("Hello out there."); System.out.println("Want to talk some more?"); System.out.println("Answer y for yes or n for no."); char answerLetter; answerLetter = SavitchIn.readLineNonwhiteChar(); if (answerLetter == 'y') System.out.println("Nice weather we are having."); System.out.println("Good-bye."); System.out.println("Press enter key to end..."); String junk; junk = SavitchIn.readLine(); } A Sample Java Program

41 Explanation of Code... l Code to begin the program (to be explained later): public class FirstProgram { public static void main(String[ ] args) { l Java applications all have similar code at the beginning »The name of the class differs from one program to another. »Other information about the class might also be included on the first line.

42 Explanation of Code... l Code to display a text string: System.out.println("Hello out there."); System.out.println("Want to talk some more?"); System.out.println("Answer y for yes or n for no."); »Note the “dot” operator »System.out is an object »println is a method that it carries out »double-quoted text inside the parentheses is an argument to the method »general syntax: ObjectName.MethodName(Arguments)

43 … Explanation of Code... Code to create a variable named answerLetter to contain a single character of data: char answerLetter; l This variable is used to store the user’s response.

44 … Explanation of Code... Read a character typed in from the keyboard and store it in the variable answerLetter : answerLetter = SavitchIn.readLineNonwhiteChar(); »SavitchIn is a class used for obtaining input from the keyboard »readLineNonwhiteChar() is a method that reads a single, non-blank character from the keyboard and discards any remaining characters on the line. »the equal sign is not the same as in math; it means “assign the value on the right to the variable on the left;” in this case, store the value read from the keyboard into the variable answerLetter

45 … Explanation of Code... Question: If “=“ means “assign the value of the expression on the right to the variable on the left,” how do we indicate “equals”? Answer: use a double equals (“==“) Example: check to see if the character entered is ‘y’: if (answerLetter == 'y') »the value inside the parentheses will be True if the letter ‘y’ was typed in, otherwise it will be False (if any other letter was typed in)

46 … Explanation of Code... l Code to display the line “Nice weather we are having.” if the user entered the character ‘y’: if (answerLetter == 'y') System.out.println("Nice weather we are having."); »Note that the line will not be printed if any letter other than ‘y’ is entered. l Unconditionally display the line “Good-bye.”: System.out.println("Good-bye."); »only the previous System.out.println is conditionally printed, depending on the value entered; the next instruction is executed regardless of the value entered.

47 … Explanation of Code l Code to prevent the display from scrolling off the screen before you can read it: System.out.println("Press enter key to end program."); String junk; junk = SavitchIn.readLine(); »junk is a variable that can contain a string of characters. »readLine() is a method to read in an entire line of text. »The program halts until a character is entered. »Any character entered will make the program continue. »The character entered is assigned to the variable junk, but is ignored (it is not used). »There are no more lines of code, so the program terminates.

48 Syntax Rules for Identifiers Identifier - the name of something (e.g. a variable, object, or method) used in a Java program. Identifiers: »cannot use reserved words (e.g. “if,” “for”, etc.) (see App. 1) »must contain only letters, digits, and the underscore character, _. »cannot have a digit for the first character. –$ is allowed but has special meaning, so do not use it. »have no official length limit (there is always a finite limit, but it is very large and big enough for reasonable names). »are case sensitive! –junk, JUNK, and Junk are three valid and different identifiers, so be sure to be careful in your typing! »Note that no spaces or dots are allowed.

49 Good Programming Practice: Identifier Naming Conventions Always use meaningful names, e.g. finalExamScore, instead of something like x, or even just score. l Use only letters and digits. Capitalize interior words in multi-word names, e.g. answerLetter. l Names of classes start with an uppercase letter. »every program in Java is a class as well as a program. l Names of variables, objects, and methods start with a lowercase letter.

50 Compiling a Java Program Assuming the java compiler is already set up and all the files are in the same folder (subdirectory): l Each class used in a program should be in a separate file l The name of the file should be the same as the class except with “.java” added to it l First compile each class definition used in the program »e.g. SavitchIn in the sample program (Display 1.4, page 18) »for Sun Microsystems’ JDK (Java Development Kit), type javac SavitchIn.java »a byte-code file is created with the name SavitchIn.class l Next compile the program file: »javac.java (which creates.class )

51 Running a Java Program Only the class with public static void main(String[] args) can be run »the critical word to look for is main For Sun Microsystems’ JDK (Java Development Kit), type java » is the same name used in the original source file.java »use just ; do not use.java or.class l Note that you compile in a separate step and invoke the Java interpreter and linker when you run the program.

52 Summary Part 1 l A computer’s main memory holds both the program that is currently running and its data. l Main memory is a series of numbered locations, each one containing a single byte. l Auxiliary memory is for more or less permanent storage. l A compiler is a program that translates a high-level language, like java, into a lower level format (“byte- code” for java). l Actual translation of Java byte-code to the hardware’s specific machine code occurs at run time (it is interpreted).

53 Summary Part 2 l An algorithm is a set of instructions for solving a problem (it must be complete and precise). l An object is something that has both data and actions (methods) associated with it. l A class defines a type of object; all objects of the same class have the same methods. l Three OOP design principles are encapsulation, polymorphism, and inheritance. In a java program, a method invocation has the general form ObjectName.MethodName(Arguments)