Chapter 1            Introduction to Computers and                     Java Objects             q   Background information...
Computer Basics            q Computer system: hardware + software            q Hardware: the physical components          ...
Common Hardware Components                                                                           q     Processor (CPU)...
Physical Organization            q   Keyboard            q   Monitor            q   Chassis                »   CPU        ...
Two Kinds of Memory            q   Main                » working area                » temporarily stores program and data...
Main Memory Organization  q    Bit = one binary digit                                                     Address Data Byt...
Auxiliary Memoryr g Organization               A u x ilia r y M e m o r y O a n iz a t io n                               ...
Running a Program        Program—a set of instructions for a computer to follow                                           ...
Many Types of Programs            q   User-created applications            q   Existing applications                »   wo...
Various Types of User Interfaces            q   Command-line                » type in key words and letters               ...
Programming Language                  Hierarchy                H ig h - L e v e l L a n g u a g e ( H L L )               ...
The highs and lows               of programming languages ...High-Level Language (HLL)                                    ...
Assembly Language                                       (middle level)            q   a more or less human readable versio...
Getting from Source to Machine Code   q        “Compiling a program”            translating from a high-level language sou...
Compilers vs. Assemblers vs. Interpreters     q      Compilers and Assemblers             » translation is a separate user...
Java Program Translation                                                           Java Program                     Data f...
Java Byte Code            q   generated by Java compiler                » Instead of generating machine language as most  ...
Why Use Byte Code?            Disadvantages:            q requires both compiler and interpreter            q slower progr...
Java Program Translation Including Linker   Java Program         Previously Compiled Helper Programs       Data for Java P...
Object-Oriented Programming: OOP  q    A design and programming technique  q    Some terminology:        » object - usuall...
Example of an Object Class                               Class: Automobile            Data Items:                         ...
Why OOP?  q    Save development time (and cost) by reusing code       » once an object class is created it can be used in ...
Design Principles of OOP                Three main design principles of Object-                Oriented Programming(OOP): ...
Encapsulation            q   Encapsulation means to design, produce, and                describe software so that it can b...
Polymorphism            q   Polymorphism—the same word or phrase can be                mean different things in different ...
Inheritance            q   Inheritance—a way of organizing classes            q   Term comes from inheritance of traits li...
An Inheritance Hierarchy                                             Vehicle            Automobile                    Moto...
Algorithms            q   Algorithm - a set of instructions (steps) for solving a                problem.                 ...
Example of an Algorithm     Algorithm that determines the total cost of a list of items:     1. Write the number 0 on the ...
Reusable Components     Advantages of using reusable components:     q saves time and money     q components that have bee...
Program Design Process            q   Design, then code            q   Design process                »   define the proble...
Testing and Debugging            q   Even with careful programming, your                code could still contain errors an...
Types of Errors            q   Syntax                                          q     Run-Time                             ...
Syntax            q   The set of grammar rules for a programming                language is called the syntax.            ...
Syntax Errors        q   caught by compiler (“compiler-time error”)        q   automatically found, usually the easiest to...
Run-Time Errors            q   An execution error (during run-time)            q   Not always so easy to fix            q ...
Logic Errors            Just because it compiles and runs without getting an              error message does not mean the ...
Logic Error Examples            q   Algorithm Error:                » averageOfFiveScores = SumOfScores/2                 ...
Finally! Now, a taste of Java!  History  q 1991 - James Gosling, Sun Microsystems, Inc.  q originally a language for progr...
Applets vs. Java Applications            q   Applets                » Java programs intended to be downloaded via the WWW ...
public class FirstProgram     {                                                      A Sample Java Program            publ...
Explanation of Code ...        q   Code to begin the program (to be explained later):            public class FirstProgram...
Explanation of Code ...   q Code to display a text string:   System.out.println("Hello out there.");   System.out.println(...
… Explanation of Code ...            q   Code to create a variable named answerLetter to                contain a single c...
… Explanation of Code ...  q    Read a character typed in from the keyboard and store it in       the variable answerLette...
… Explanation of Code ...            Question: If “=“ means “assign the value of the              expression on the right ...
… Explanation of Code ...    q       Code to display the line “Nice weather we are having.” if the user            entered...
… Explanation of Code            q Code to prevent the display from scrolling off the screen before              you can r...
Compiling a Java Program     Assuming the java compiler is already set up and all the       files are in the same folder (...
Running a Java Program     q      Only the class with public static void            main(String[] args)can be run         ...
Summary                                                     Part 1            q   A computer’s main memory holds both the ...
Summary                                                  Part 2        q   An algorithm is a set of instructions for solvi...
Upcoming SlideShare
Loading in …5
×

Ch01

688 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
688
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
16
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Ch01

  1. 1. Chapter 1 Introduction to Computers and Java Objects q Background information » important regardless of programming language q Introduction to JavaChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch
  2. 2. Computer Basics q Computer system: hardware + software q Hardware: the physical components q Software: the instructions that tell the hardware what to doChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch
  3. 3. Common Hardware Components q Processor (CPU) Standard Hardware » Central Processing Unit » Interprets and executes the Organization instructions q Memory Memory » main & auxiliary (main & auxiliary) » holds data and instructions q Input device(s) » mouse, keyboard, etc. Input Output Processor Devices (such as mouse and (CPU) Devices (such as video q Output device(s) keyboard) display or printer) » video display, printer, etc. q CPU and memory are physically housed togetherChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch
  4. 4. Physical Organization q Keyboard q Monitor q Chassis » CPU » memory » disk drives » I/O connectors » etc.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch
  5. 5. Two Kinds of Memory q Main » working area » temporarily stores program and data (while program is executing) q Auxiliary » permanent (more or less) » saves program and results » includes floppy & hard disk drives, CDs, tape, etc.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch
  6. 6. Main Memory Organization q Bit = one binary digit Address Data Byte » Binary digit can have 3021 1111 0000 Item 1: 2 bytes only one of two values, 0 stored 3022 1100 1100 or 1 3023 1010 1010 Item 2: 1 byte q Byte = 8 bits stored q “Byte Addressable” 3024 1100 1110 Item 3: 3 bytes stored » Main memory is a list of 3025 0011 0001 numbered locations that 3026 1110 0001 contain one byte of data 3027 0110 0011 Item 4: 2 bytes in each location stored q Number of bytes per data 3028 1010 0010 item may vary 3029 … Next Item, etc.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch
  7. 7. Auxiliary Memoryr g Organization A u x ilia r y M e m o r y O a n iz a t io n M a in ( R o o t ) D ir e c t o r y / F o ld e r F ile s S u b d ir e c t o r y S u b d ir e c t o r y F ile s S u b d ir e c t o r y S u b d ir e c t o r y S u b d ir e c t o r y F ile s F ile s F ile s S u b d ir e c t o r y F ile sChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch
  8. 8. Running a Program Program—a set of instructions for a computer to follow Program Data Computer Output (input for the program)Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch
  9. 9. Many Types of Programs q User-created applications q Existing applications » word-processor/editor » web browser » compiler or assembler » etc. q Operating System » DOS, Microsoft Windows, MacOS, Linux, UNIX, etc.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch
  10. 10. Various Types of User Interfaces q Command-line » type in key words and letters » DOS and UNIX q Menu » parts of DOS and Windows q GUI (Graphical User Interface) » click on icon » also called “event-driven” » MacOS, WindowsChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 1
  11. 11. Programming Language Hierarchy H ig h - L e v e l L a n g u a g e ( H L L ) A s s e m b ly L a n u a g e M a c h in e L a n g u a g e H a rd w a reChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 1
  12. 12. The highs and lows of programming languages ...High-Level Language (HLL) Machine Language » closest to natural (lowest level) language » least natural language for » words, numbers, and humans, most natural language for hardware math symbols » just 0s and 1s » not directly understood by » directly understood by hardware hardware » “portable” source code » not portable (hardware (hardware independent) dependent) » Java, C, C++, COBOL, FORTRAN, BASIC, Lisp, Ada, etc.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 1
  13. 13. Assembly Language (middle level) q a more or less human readable version of machine language q words, abbreviations, letters and numbers replace 0s and 1s q easily translated from human readable to machine executable code q like machine code, not portable (hardware dependent)Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 1
  14. 14. Getting from Source to Machine Code q “Compiling a program” translating from a high-level language source code to machine (object, or executable) code. q “Compiler” a program that translates HLL source code to machine (object, or executable) code. q “Assembly” translating from assemble language source code to machine (object, or executable) code. q “Assembler” a program that translates assembly source code to machine (object, or executable) code. q Compilers need to know the specific target hardwareChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 1
  15. 15. Compilers vs. Assemblers vs. Interpreters q Compilers and Assemblers » translation is a separate user step » translation is “off-line,” i.e. not at run time q 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, Source Object Code Assembler, or Code InterpreterChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 1
  16. 16. Java Program Translation Java Program Data for Java Program q Both Compilation and Interpretation Java Compiler Java q Intermediate Code: Virtual Byte-Code “Byte Code” Program Machine » similar to assembly Byte-Code Interpreter code, but hardware independent Machine-Language Instructions q Interpreter translates from generic byte Computer Execution code to hardware- of Machine-Language Instructions specific machine code Output of Java ProgramChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 1
  17. 17. Java Byte Code q generated by Java compiler » Instead of generating machine language as most compilers do, the Java compiler generates byte code. q easily translated to machine language of various kinds of computers q executed by Java interpreter q invisible to programmer » You dont have to know anything about how byte code works to write a Java program.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 1
  18. 18. Why Use Byte Code? Disadvantages: q requires both compiler and interpreter q slower program execution Advantages: q portability » very important » same program can run on computers of different types (useful with the Internet) » Java interpreter for new types of computers can be made quicklyChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 1
  19. 19. Java Program Translation Including Linker Java Program Previously Compiled Helper Programs Data for Java Program Java Compiler Java Byte-Code Virtual Program MachineByte-Code Interpreter Machine-Language Instructions Linker Computer Execution of Machine-Language Instructions Output of Java Program
  20. 20. Object-Oriented Programming: OOP q A design and programming technique q 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) q Objects have both data and methods q Objects of the same class have the same data elements and methods q Objects send and receive messages to invoke actionsChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 2
  21. 21. Example of an Object Class Class: Automobile Data Items: Methods: » manufacturer’s name » Define data items » model name (specify manufacturer’s » name, model, year, etc.) year made » Change a data item » color (color, engine, etc.) » number of doors » Display data items » size of engine » Calculate cost » etc. » etc.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 2
  22. 22. Why OOP? q Save development time (and cost) by reusing code » once an object class is created it can be used in other applications q Easier debugging » classes can be tested independently » reused objects have already been testedChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 2
  23. 23. Design Principles of OOP Three main design principles of Object- Oriented Programming(OOP): q Encapsulation q Polymorphism q InheritanceChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 2
  24. 24. Encapsulation q Encapsulation means to design, produce, and describe software so that it can be easily used without knowing the details of how it works. q Also known as information hiding An analogy: q 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. q Instead you only have to know how to use the controls.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 2
  25. 25. Polymorphism q Polymorphism—the same word or phrase can be mean different things in different contexts q Analogy: in English, bank can mean side of a river or a place to put money q In Java, two or more classes could each have a method called output q Each output method would do the right thing for the class that it was in. q One output might display a number whereas a different one might display a name.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 2
  26. 26. Inheritance q Inheritance—a way of organizing classes q Term comes from inheritance of traits like eye color, hair color, and so on. q Classes with properties in common can be grouped so that their common properties are only defined once.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 2
  27. 27. An Inheritance Hierarchy Vehicle Automobile Motorcycle Bus Sedan Sports Car School Bus Luxury Bus What properties does each vehicle inherit from the types of vehicles above it in the diagram?Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 2
  28. 28. Algorithms q Algorithm - a set of instructions (steps) for solving a problem. » must be precise » must be complete q 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 languageChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 2
  29. 29. 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 boardChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 2
  30. 30. Reusable Components Advantages of using reusable components: q saves time and money q components that have been used before are often better tested and more reliable than new software Make your classes reusable: q encapsulation q general classes have a better chance of being reused than ad hoc classesChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 3
  31. 31. Program Design Process q Design, then code q 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 retestChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 3
  32. 32. Testing and Debugging q Even with careful programming, your code could still contain errors and must be thoroughly tested. q Bug—a mistake in a program q Debugging—fixing mistakes in a programChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 3
  33. 33. Types of Errors q Syntax q Run-Time q LogicChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 3
  34. 34. Syntax q The set of grammar rules for a programming language is called the syntax. q The compiler checks your program to make sure it is a valid Java program. q If your program is not a valid Java program, then the compiler outputs a message indicating a syntax error.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 3
  35. 35. Syntax Errors q caught by compiler (“compiler-time error”) q automatically found, usually the easiest to fix q cannot run code until all syntax errors are fixed q error message may be misleading Example: Misspelling a command, for example “rturn” instead of “return”Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 3
  36. 36. Run-Time Errors q An execution error (during run-time) q Not always so easy to fix q Error message may or may not be helpful q Not detected by the compiler. Example: Division by zero - if your program attempts to divide by zero it automatically terminates and prints an error message.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 3
  37. 37. Logic Errors Just because it compiles and runs without getting an error message does not mean the code is correct! q 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 q Generally the most difficult to find and fix q Need to be alert and test thoroughly » think about test cases and predict results before executing the codeChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 3
  38. 38. Logic Error Examples q Algorithm Error: » averageOfFiveScores = SumOfScores/2 (should divide by 5) q Implementation Error: » typed in wrong symbol in source code - sum = a - b; (should be sum = a + b;)Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 3
  39. 39. Finally! Now, a taste of Java! History q 1991 - James Gosling, Sun Microsystems, Inc. q originally a language for programming home appliances q later (1994) used for World Wide Web applications (since byte code can be downloaded and run without compiling it) q eventually used as a general-purpose programming language (for the same reason as above plus it is object- oriented) q 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.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 3
  40. 40. Applets vs. Java Applications q Applets » Java programs intended to be downloaded via the WWW and run immediately » “little applications” » requires a web browser q Applications » Java programs intended to be installed then run » often larger applications q Slightly different programming for each, but both are easy to doChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 4
  41. 41. public class FirstProgram { A Sample Java Program 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(); } }Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 4
  42. 42. Explanation of Code ... q Code to begin the program (to be explained later): public class FirstProgram { public static void main(String[ ] args) { q 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.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 4
  43. 43. Explanation of Code ... q 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: Object_Name.Method_Name(Arguments)Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 4
  44. 44. … Explanation of Code ... q Code to create a variable named answerLetter to contain a single character of data: char answerLetter; q This variable is used to store the user’s response.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 4
  45. 45. … Explanation of Code ... q 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 answerLetterChapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 4
  46. 46. … 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)Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 4
  47. 47. … Explanation of Code ... q 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. q 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.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 4
  48. 48. … Explanation of Code q 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.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 4
  49. 49. Compiling a Java Program Assuming the java compiler is already set up and all the files are in the same folder (subdirectory): q Each class used in a program should be in a separate file q The name of the file should be the same as the class except with “.java” added to it q 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 q Next compile the program file: » javac <file>.java (which creates <file>.class)Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 4
  50. 50. Running a Java Program q Only the class with public static void main(String[] args)can be run » the critical word to look for is main q For Sun Microsystems’ JDK (Java Development Kit), type java <file> » <file> is the same name used in the original source file <file>.java » use just <file>; do not use <file>.java or <file>.class q Note that you compile in a separate step and invoke the Java interpreter and linker when you run the program.Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 5
  51. 51. Summary Part 1 q A computer’s main memory holds both the program that is currently running and its data. q Main memory is a series of numbered locations, each one containing a single byte. q Auxiliary memory is for more or less permanent storage. q A compiler is a program that translates a high-level language, like java, into a lower level format (“byte- code” for java). q Actual translation of Java byte-code to the hardware’s specific machine code occurs at run time (it is interpreted).Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 5
  52. 52. Summary Part 2 q An algorithm is a set of instructions for solving a problem (it must be complete and precise). q An object is something that has both data and actions (methods) associated with it. q A class defines a type of object; all objects of the same class have the same methods. q Three OOP design principles are encapsulation, polymorphism, and inheritance. q In a java program, a method invocation has the general form Object_Name.Method_Name(Arguments)Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 5

×