Chapter 1


            Introduction to Computers and
                     Java Objects
             q   Background information
                 » important regardless of programming language


             q   Introduction to Java




Chapter 1          Java: an Introduction to Computer Science & Programming - Walter Savitch
Computer Basics

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




Chapter 1            Java: an Introduction to Computer Science & Programming - Walter Savitch
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 together


Chapter 1                        Java: an Introduction to Computer Science & Programming - Walter Savitch
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
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
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
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 s

Chapter 1          Java: an Introduction to Computer Science & Programming - Walter Savitch
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
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
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, Windows

Chapter 1                Java: an Introduction to Computer Science & Programming - Walter Savitch   1
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 re

Chapter 1      Java: an Introduction to Computer Science & Programming - Walter Savitch   1
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
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
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 hardware

Chapter 1                 Java: an Introduction to Computer Science & Programming - Walter Savitch   1
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
                                                 Interpreter

Chapter 1                 Java: an Introduction to Computer Science & Programming - Walter Savitch    1
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 Program

Chapter 1               Java: an Introduction to Computer Science & Programming - Walter Savitch                    1
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 don't 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
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 quickly

Chapter 1               Java: an Introduction to Computer Science & Programming - Walter Savitch   1
Java Program Translation Including Linker
   Java Program         Previously Compiled Helper Programs       Data for Java Program


   Java Compiler
                                                  Java
    Byte-Code                                    Virtual
     Program
                                                Machine
Byte-Code Interpreter

 Machine-Language
    Instructions

                    Linker


                                     Computer Execution
                               of Machine-Language Instructions


                                  Output of Java Program
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 actions

Chapter 1          Java: an Introduction to Computer Science & Programming - Walter Savitch   2
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
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 tested


Chapter 1         Java: an Introduction to Computer Science & Programming - Walter Savitch   2
Design Principles of OOP

                Three main design principles of Object-
                Oriented Programming(OOP):
            q   Encapsulation
            q   Polymorphism
            q   Inheritance



Chapter 1               Java: an Introduction to Computer Science & Programming - Walter Savitch   2
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
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
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
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
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
                  language
Chapter 1                 Java: an Introduction to Computer Science & Programming - Walter Savitch   2
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


Chapter 1           Java: an Introduction to Computer Science & Programming - Walter Savitch   2
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 classes
Chapter 1        Java: an Introduction to Computer Science & Programming - Walter Savitch   3
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 retest

Chapter 1                  Java: an Introduction to Computer Science & Programming - Walter Savitch   3
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 program




Chapter 1              Java: an Introduction to Computer Science & Programming - Walter Savitch   3
Types of Errors

            q   Syntax

                                          q     Run-Time

                                                                                                    q   Logic



Chapter 1                Java: an Introduction to Computer Science & Programming - Walter Savitch               3
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
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
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
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 code

Chapter 1                   Java: an Introduction to Computer Science & Programming - Walter Savitch   3
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
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
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 do


Chapter 1                 Java: an Introduction to Computer Science & Programming - Walter Savitch   4
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
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
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
… 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
… 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 answerLetter
Chapter 1                Java: an Introduction to Computer Science & Programming - Walter Savitch   4
… 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
… 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
… 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
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
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
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
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

More Related Content

PPT
Savitch Ch 03
PPT
PPT
JavaYDL1
PPT
Computer Repair and Maintenance for Students.ppt
PPT
01slide
PDF
Java Performance
PPTX
1.1 work sheet 1
PPS
C language computer introduction to the computer hardware
Savitch Ch 03
JavaYDL1
Computer Repair and Maintenance for Students.ppt
01slide
Java Performance
1.1 work sheet 1
C language computer introduction to the computer hardware

Similar to Ch01 (20)

PPT
ydtyT01 a computerintrohardware
PPT
T01 a computerintrohardware
PPT
module1_computerbasics1 - Copy.ppt
PPTX
Lesson 1 - Presentation - introduction to computer main components.pptx
DOC
Scheme Of Work Imd 203
PDF
Computer and Information Technology
PPT
Computer Basics Operation It includes two lessons: Lesson 1: Introduction to ...
PPT
computer_basics hardware of computer system
PPTX
Intro (lesson1)comp arch
PPTX
Computer Hardware and Software.pptx_20250727_161316_0000.pptx
PPT
Module1 computerbasics1
PPT
PPT
Introduction to computer
PDF
Introduction to CUDA programming in C language
PDF
1.1 Hardware and Software.pdf
PDF
1.1 Hardware and Software.pdf
PDF
Introduction to AIoT & TinyML - with Arduino
PPTX
First lecture
PPTX
The Next Step of OpenStack Evolution for NFV Deployments
PPT
[Challenge:Future] Introduction to computer archtecture
ydtyT01 a computerintrohardware
T01 a computerintrohardware
module1_computerbasics1 - Copy.ppt
Lesson 1 - Presentation - introduction to computer main components.pptx
Scheme Of Work Imd 203
Computer and Information Technology
Computer Basics Operation It includes two lessons: Lesson 1: Introduction to ...
computer_basics hardware of computer system
Intro (lesson1)comp arch
Computer Hardware and Software.pptx_20250727_161316_0000.pptx
Module1 computerbasics1
Introduction to computer
Introduction to CUDA programming in C language
1.1 Hardware and Software.pdf
1.1 Hardware and Software.pdf
Introduction to AIoT & TinyML - with Arduino
First lecture
The Next Step of OpenStack Evolution for NFV Deployments
[Challenge:Future] Introduction to computer archtecture
Ad

Recently uploaded (20)

PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Architecture types and enterprise applications.pdf
PDF
Hindi spoken digit analysis for native and non-native speakers
PPTX
Modernising the Digital Integration Hub
PDF
A review of recent deep learning applications in wood surface defect identifi...
PDF
Zenith AI: Advanced Artificial Intelligence
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PPTX
Benefits of Physical activity for teenagers.pptx
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PPT
Module 1.ppt Iot fundamentals and Architecture
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
DOCX
search engine optimization ppt fir known well about this
PPTX
Chapter 5: Probability Theory and Statistics
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Architecture types and enterprise applications.pdf
Hindi spoken digit analysis for native and non-native speakers
Modernising the Digital Integration Hub
A review of recent deep learning applications in wood surface defect identifi...
Zenith AI: Advanced Artificial Intelligence
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
Benefits of Physical activity for teenagers.pptx
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
sustainability-14-14877-v2.pddhzftheheeeee
Module 1.ppt Iot fundamentals and Architecture
A comparative study of natural language inference in Swahili using monolingua...
Taming the Chaos: How to Turn Unstructured Data into Decisions
Group 1 Presentation -Planning and Decision Making .pptx
search engine optimization ppt fir known well about this
Chapter 5: Probability Theory and Statistics
1 - Historical Antecedents, Social Consideration.pdf
Univ-Connecticut-ChatGPT-Presentaion.pdf
A contest of sentiment analysis: k-nearest neighbor versus neural network
Ad

Ch01

  • 1. Chapter 1 Introduction to Computers and Java Objects q Background information » important regardless of programming language q Introduction to Java Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch
  • 2. Computer Basics q Computer system: hardware + software q Hardware: the physical components q Software: the instructions that tell the hardware what to do Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch
  • 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 together Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch
  • 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. 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. 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. 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 s Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch
  • 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. 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. 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, Windows Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 1
  • 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 re Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 1
  • 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. 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. 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 hardware Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 1
  • 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 Interpreter Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 1
  • 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 Program Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 1
  • 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 don't 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. 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 quickly Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 1
  • 19. Java Program Translation Including Linker Java Program Previously Compiled Helper Programs Data for Java Program Java Compiler Java Byte-Code Virtual Program Machine Byte-Code Interpreter Machine-Language Instructions Linker Computer Execution of Machine-Language Instructions Output of Java Program
  • 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 actions Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 2
  • 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. 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 tested Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 2
  • 23. Design Principles of OOP Three main design principles of Object- Oriented Programming(OOP): q Encapsulation q Polymorphism q Inheritance Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 2
  • 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. 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. 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. 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. 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 language Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 2
  • 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 board Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 2
  • 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 classes Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 3
  • 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 retest Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 3
  • 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 program Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 3
  • 33. Types of Errors q Syntax q Run-Time q Logic Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 3
  • 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. 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. 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. 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 code Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 3
  • 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. 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. 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 do Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 4
  • 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. 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. 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. … 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. … 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 answerLetter Chapter 1 Java: an Introduction to Computer Science & Programming - Walter Savitch 4
  • 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. … 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. … 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. 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. 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. 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. 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