Chapter 1

Chapter 1

Chapter 1: Creating Java Programs Objectives, Part 1 Define basic programming terminology Compare procedural and object-oriented programming Describe the features of the Java programming language Analyze a Java application that produces console output Java Programming, Seventh Edition 2 Objectives, Part 2

Compile a Java class and correct syntax errors Run a Java application and correct logical errors Add comments to a Java class Create a Java application that produces GUI output Find help Java Programming, Seventh Edition 3 Learning Programming

Terminology, Part 1 Computer program A set of written instructions that tells the computer what to do Machine language The most basic circuitry-level language A low-level programming language Java Programming, Seventh Edition 4 Learning Programming Terminology, Part 2 High-level programming language Allows you to use a vocabulary of reasonable terms

Syntax A specific set of rules for the language Program statements Similar to English sentences Commands to carry out program tasks Java Programming, Seventh Edition 5 Learning Programming Terminology, Part 3 Compiler or interpreter Translates language statements into machine code

Syntax error Misuse of language rules A misspelled programming language word Debugging Freeing program of all errors Logic errors Also called semantic errors Incorrect order or procedure The program may run but provide inaccurate output Java Programming, Seventh Edition 6 Comparing Procedural and Object-Oriented

Programming Concepts, Part 1 Procedural programming Sets of operations executed in sequence Variables Named computer memory locations that hold values Procedures Individual operations grouped into logical units Object-oriented programs Create classes Blueprints for an object Create objects from classes Create applications Java Programming, Seventh Edition

7 Comparing Procedural and Object-Oriented Programming Concepts, Part 2 Object-oriented programming was used most frequently for two major types of applications Computer simulations Graphical user interfaces (GUIs) Not all object-oriented programs are written to use a GUI Object-oriented programming differs from traditional procedural programming Basic concepts Polymorphism Inheritance Encapsulation

Java Programming, Seventh Edition 8 Understanding Classes, Objects, and Encapsulation, Part 1 Class Describes objects with common properties A definition An instance Attributes Characteristics that define an object Differentiate objects of the same class The value of attributes is an objects state

Objects Specific, concrete instances of a class Java Programming, Seventh Edition 9 Understanding Classes, Objects, and Encapsulation, Part 2 Java Programming, Seventh Edition 10 Understanding Classes, Objects, and Encapsulation, Part 3 Method A self-contained block of program code that carries out an

action Similar to a procedure Encapsulation Conceals internal values and methods from outside sources Provides security Keeps data and methods safe from inadvertent changes Java Programming, Seventh Edition 11 Understanding Inheritance and Polymorphism Inheritance An important feature of object-oriented programs

Classes share attributes and methods of existing classes but with more specific features Helps you understand real-world objects Polymorphism Means many forms Allows the same word to be interpreted correctly in different situations based on context Java Programming, Seventh Edition 12 Features of the Java Programming Language, Part 1 Java

Developed by Sun Microsystems An object-oriented language General-purpose Advantages Security features Architecturally neutral Java Programming, Seventh Edition 13 Features of the Java Programming Language, Part 2

Java (contd.) Can be run on a wide variety of computers Does not execute instructions on the computer directly Runs on a hypothetical computer known as a Java Virtual Machine (JVM) Source code Programming statements written in high-level programming language Java Programming, Seventh Edition 14 Features of the Java Programming Language, Part 3 Development environment

A set of tools used to write programs Bytecode Statements saved in a file A binary program into which the Java compiler converts source code Java interpreter Checks bytecode and communicates with the operating system Executes bytecode instructions line by line within the Java Virtual Machine Java Programming, Seventh Edition 15 Features of the Java Programming

Language, Part 4 Java Programming, Seventh Edition 16 Java Program Types Applets Programs embedded in a Web page Java applications Called Java stand-alone programs Console applications Support character output Windowed applications Menus

Toolbars Dialog boxes Java Programming, Seventh Edition 17 Analyzing a Java Application that Produces Console Output, Part 1 Even the simplest Java application involves a fair amount of confusing syntax Print First Java application on the screen Java Programming, Seventh Edition 18

Analyzing a Java Application that Produces Console Output, Part 2 Java Programming, Seventh Edition 19 Understanding the Statement that Produces the Output, Part 1 Literal string Will appear in output exactly as entered Written between double quotation marks Arguments Pieces of information passed to a method Method

Requires information to perform its task System class Refers to the standard output device for a system Java Programming, Seventh Edition 20 Understanding the Statement that Produces the Output, Part 2 Java Programming, Seventh Edition 21 Understanding the First Class,

Part 1 Everything used within a Java program must be part of a class Define a Java class using any name or identifier Requirements for identifiers Must begin with one of the following: Letter of the English alphabet Non-English letter (such as or )) Underscore Dollar sign Cannot begin with a digit

Java Programming, Seventh Edition 22 Understanding the First Class, Part 2 Requirements for identifiers (contd.) Can only contain: Letters Digits Underscores Dollar signs

Cannot be a Java reserved keyword Cannot be true, false, or null Access specifier Defines how a class can be accessed Java Programming, Seventh Edition 23 Understanding the First Class, Part 3

abstract assert boolean break byte case catch

char class const continue default do

double else enum extends final finally float for goto if implements import instanceof

int interface

long native new package private protected public return short static strictfp

super switch synchronized this throw throws transient try void volatile

while Table 1-1 Java reserved keywords Java Programming, Seventh Edition 24 Understanding the First Class, Part 4 Class Name Description Undergradstudent New words are not indicated with initial uppercase letters, making this identifier difficult to read

Inventory_Item Underscore is not commonly used to indicate new words BUDGET2012 Using all uppercase letters for class identifiers is not conventional budget2012 Conventionally, class names do not begin with a lowercase letter Table 1-3 Legal but unconventional and nonrecommended class names in Java Java Programming, Seventh Edition

25 Understanding the First Class, Part 5 Class Name Description Inventory Item Space character is illegal in an identifier class class is a reserved word 2012Budget

Class names cannot begin with a digit phone # The number symbol (#) is illegal in an identifier Table 1-4 Some illegal class names in Java Java Programming, Seventh Edition 26 Understanding the First Class, Part 6 Java Programming, Seventh Edition

27 Indent Style For every opening curly brace ( { ) in a Java program, there must be a corresponding closing curly brace (}) Placement of the opening and closing curly braces is not important to the compiler Java Programming, Seventh Edition 28 Understanding the main() Method, Part 1 static

A reserved keyword Means the method is accessible and usable even though no objects of the class exist void Use in the main() method header Does not indicate the main() method is empty Indicates the main() method does not return a value when called Does not mean that main() doesnt produce output Java Programming, Seventh Edition 29 Understanding the main() Method, Part 2

Figure 1-7 The parts of a typical main() method Java Programming, Seventh Edition 30 Understanding the main() Method, Part 3 Java Programming, Seventh Edition 31 Saving a Java Class Saving a Java class Save the class in a file with exactly the same name and .java extension For public classes, class name and filename must match exactly

Java Programming, Seventh Edition 32 Compiling a Java Class and Correcting Syntax Errors, Part 1 Compiling a Java class Compile the source code into bytecode Translate the bytecode into executable statements Using a Java interpreter Type javac First.java Compilation outcomes javac is an unrecognized command Program language error messages

No messages indicating successful completion Java Programming, Seventh Edition 33 Compiling a Java Class and Correcting Syntax Errors, Part 2 Reasons for error messages Misspelled the command javac A misspelled filename Not within the correct subfolder or subdirectory on the command line Improper installation of Java Java Programming, Seventh Edition

34 Correcting Syntax Errors The first line of the error message displays: The name of the file where the error was found The line number The nature of the error Next lines identify: The symbol The location Compile-time error The compiler detects a violation of language rules Refuses to translate the class to machine code Parsing

Used by the process compiler to divide source code into meaningful portions Java Programming, Seventh Edition 35 Running a Java Application and Correcting Logical Errors, Part 1 Run the application from the command line Type java First Shows the applications output in the command window The class is stored in a folder named Java on the C drive Java Programming, Seventh Edition

36 Running a Java Application and Correcting Logical Errors, Part 2 Java Programming, Seventh Edition 37 Modifying a Compiled Java Class, Part 1

Modify the text file that contains the existing class Save the file with changes using the same filename Compile the class with the javac command Interpret the class bytecode and execute the class using the java command Java Programming, Seventh Edition 38 Modifying a Compiled Java Class, Part 2 Figure 1-18 First class containing output modified from the original version Java Programming, Seventh Edition

39 Correcting Logical Errors Logic error The syntax is correct but incorrect results were produced when executed Run-time error Not detected until execution Often difficult to find and resolve Java Programming, Seventh Edition 40 Adding Comments to a Java Class, Part 1

Program comments Nonexecuting statements added to a program for documentation Use to leave notes for yourself or others Include the author, date, and classs name or function Comment out a statement Turn it into a comment The compiler does not translate, and the JVM does not execute its command Java Programming, Seventh Edition 41 Adding Comments to a Java Class, Part 2

Types of Java comments Line comments Start with two forward slashes (//) Continue to the end of the current line Do not require an ending symbol Block comments Start with a forward slash and an asterisk (/*) End with an asterisk and a forward slash (*/) Java Programming, Seventh Edition 42 Adding Comments to a Java Class, Part 3 Types of Java comments (contd.)

Javadoc comments A special case of block comments Begin with a slash and two asterisks (/**) End with an asterisk and a forward slash (*/) Use to generate documentation Java Programming, Seventh Edition 43 Adding Comments to a Java Class, Part 4

Figure 1-21 A program segment containing several comments Java Programming, Seventh Edition 44 Creating a Java Application that Produces GUI Output, Part 1 JOptionPane Produces dialog boxes Dialog box A GUI object resembling a window Messages placed for display import statement

Use to access a built-in Java class Package A group of classes Java Programming, Seventh Edition 45 Creating a Java Application that Produces GUI Output, Part 2 Figure 1-22 The parts of a typical FirstDialog class Java Programming, Seventh Edition 46

Creating a Java Application that Produces GUI Output, Part 3 Figure 1-23 Output of the FirstDialog application Java Programming, Seventh Edition 47 Finding Help Java API Also called the Java class library Provides prewritten information about Java classes FAQs on the Java Web site Java Development Kit (JDK)

A software development kit (SDK) of programming tools Free to download Java Programming, Seventh Edition 48 You Do It Your First Application Compiling a Java Class Adding Comments to a Class

Creating a Dialog Box Exploring the Java Web Site Java Programming, Seventh Edition 49 Dont Do It Dont forget the files name must match the class name Dont confuse these terms: Parentheses, braces, brackets, curly braces, square brackets, and angle brackets Dont forget to end a block comment Dont forget that Java is case sensitive Dont forget to end every statement with a semicolon

Do not end class or method headers with a semicolon Dont forgot to recompile when making changes Java Programming, Seventh Edition 50 Summary, Part 1 Computer program A set of instructions that tells a computer what to do Object-oriented programs Classes Objects Applications Java Virtual Machine (JVM)

A standardized hypothetical computer Everything in a Java program must be part of a class Java Programming, Seventh Edition 51 Summary, Part 2 Access specifier A word that defines circumstances under which a class can be accessed All Java applications must have a method named main() Program comments Nonexecuting statements Add to a file for documentation

javac A compile command Java Programming, Seventh Edition 52 Summary, Part 3 java An execute command JOptionPane A GUI Provides methods for creating dialogs Java Programming, Seventh Edition

53

Recently Viewed Presentations

  • Types of Dominance Complete Dominance  Genetic crosses that

    Types of Dominance Complete Dominance Genetic crosses that

    A Heterozygous (RW) flower is crossed with a Homozygous (RR) flower: Complete a Punnett Square for this cross. What color is the Heterozygous parent flower? What color is the Homozygous (RR) parent flower? ... Blood Donors & Receivers. Sex Linked...
  • Saint Nicholas (santa claus) Feast day December 6th

    Saint Nicholas (santa claus) Feast day December 6th

    and builds up love and hope in peoples hearts . Santa may be the jolly man with the beard . who makes you laugh once a year. Jesus offers people joy and laughter that lasts forever, and is their strength....
  • Reading in Grade 3: A parent's guide to "read to achieve"

    Reading in Grade 3: A parent's guide to "read to achieve"

    The TRC assessment is administered in a one-on-one setting and requires students to read books of different levels and answer questions in an oral and written manner. Mclass/Dibels assessments (cont) The TRC levels are conveyed using letters of the alphabet....
  • Knowledge Translation Basics - MSFHR

    Knowledge Translation Basics - MSFHR

    Synthesis - the contextualization and integration of research findings of individual research studies within the larger body of knowledge on the topic . E.g., practice guidelines. result from a consensus conference or expert panel. realist synthesis. narrative synthesis. systematic or...
  • The Water Cycle The Water Cycle THE SUN

    The Water Cycle The Water Cycle THE SUN

    THE SUN DRIVES THE WATER CYCLE. THE SUN DRIVES THE WATER CYCLE. THE SUN DRIVES THE WATER CYCLE. Only 3% of Earth's water is freshwater. Only 30% of ALL freshwater is in liquid form: 1% on the surface 29% underground...
  • Kentucky Lead Workgroup Lead Corrosion and Treatment KWWOA

    Kentucky Lead Workgroup Lead Corrosion and Treatment KWWOA

    Orthophosphate (PO. 4)Best at pH 7.2 to 7.8. Issues: Microbial? Wastewater Treatment? Form insoluble Pb(IV) scale . High oxidation state, via maintenance of free Cl. 2 . residualCl/SO. 4. Ratio Higher chloride-to-sulfate mass ratio (CSMR) tends to increase lead release...
  • Cmtc - Outline

    Cmtc - Outline

    Emotional Intelligence View 360 Administration and Interpretation A recent meta-analysis of 26 longitudinal studies indicate significant but small effect sizes suggesting that it is unrealistic to expect large performance improvement after people receive 360-degree feedback Smither, J., London, M., &...
  • Today's hypothesis

    Today's hypothesis

    The Assertive Mentoring system is designed to monitor and address gaps in children's skills and knowledge in order to progress to the next Stage. Assessments will be set for every child, every half term.