View
216
Download
0
Tags:
Embed Size (px)
Citation preview
CPE-101CPE-101
Clark Savage Turner, J.D., Ph.D.Clark Savage Turner, J.D., Ph.D.
[email protected]@csc.calpoly.edu
756-6133756-6133
Slides adapted for use with Kaufman and Wolz by Clark Slides adapted for use with Kaufman and Wolz by Clark S. Turner, and S. Turner, and
Some lecture slides were adapted from those developed bySome lecture slides were adapted from those developed by
John Lewis and William LoftusJohn Lewis and William Loftus
to accompany Java Software Solutions, 2d ed.to accompany Java Software Solutions, 2d ed.
Some slides adapted from slides by Carol Scheftic, Cal Poly CSC Dept.Some slides adapted from slides by Carol Scheftic, Cal Poly CSC Dept.
CPE-101
Focus of the courseFocus of the course
Object-oriented software developmentObject-oriented software development problem solvingproblem solving program design and implementationprogram design and implementation object-oriented conceptsobject-oriented concepts
objectsobjects classesclasses interfacesinterfaces inheritanceinheritance polymorphismpolymorphism
graphics and Graphical User Interfacesgraphics and Graphical User Interfaces the Java programming languagethe Java programming language
CPE-101
Programs are written to solve problems!Programs are written to solve problems!
The general steps in problem solving are:The general steps in problem solving are: Understand the problemUnderstand the problem
What is the problem? What is not part of the problem?What is the problem? What is not part of the problem? Dissect the problem into manageable pieces.Dissect the problem into manageable pieces.
Design a solutionDesign a solution Have you seen this problem before? Have you seen a similar one?Have you seen this problem before? Have you seen a similar one? Can you restate the problem? Can you solve it? Part of it?Can you restate the problem? Can you solve it? Part of it? Consider alternatives to your first solution and refine it.Consider alternatives to your first solution and refine it.
Implement the solutionImplement the solution Check each step as you proceed. Test the final solution.Check each step as you proceed. Test the final solution. If necessary, fix any problems that exist, and repeat the previous step.If necessary, fix any problems that exist, and repeat the previous step.
Reflect on what you learned from the problemReflect on what you learned from the problem What did you learn from the problem? the solution? What did you learn from the problem? the solution? What did you learn from any difficulties you encountered?What did you learn from any difficulties you encountered?
CPE-101
More on Problem SolvingMore on Problem Solving
Many software projects fail because the developer didn't Many software projects fail because the developer didn't really understand the problem to be solved.really understand the problem to be solved.
We must avoid assumptions and clarify ambiguities.We must avoid assumptions and clarify ambiguities.
As problems and their solutions become larger, we must As problems and their solutions become larger, we must organize our development into manageable pieces.organize our development into manageable pieces.
This technique is fundamental to software development.This technique is fundamental to software development.
We will dissect our solutions into pieces called classes, We will dissect our solutions into pieces called classes, objects and methods, taking an objects and methods, taking an object-oriented approach.object-oriented approach.
CPE-101
Brief Java HistoryBrief Java History
1990-95: James Gosling at Sun began to develop a new 1990-95: James Gosling at Sun began to develop a new programming language for consumer electronics software.programming language for consumer electronics software. It was originally known as OakIt was originally known as Oak It was small, reliable, and architecture independent.It was small, reliable, and architecture independent.
1990-94: Tim Berners-Lee at CERN in Geneva began to 1990-94: Tim Berners-Lee at CERN in Geneva began to develop the World Wide Web.develop the World Wide Web. It was powerful, global, and architecture independent.It was powerful, global, and architecture independent.
~1993: The Java team wrote a browser called HotJava.~1993: The Java team wrote a browser called HotJava. It was the first web browser to support Java applets.It was the first web browser to support Java applets. It demonstrated the power of Java to the rest of the programming It demonstrated the power of Java to the rest of the programming
world.world.
CPE-101
But what is Java?But what is Java?
A high-level programming language.A high-level programming language. Object-oriented.Object-oriented. Architecture-neutral and portable.Architecture-neutral and portable. Sort of interpreted, sort of compiled.Sort of interpreted, sort of compiled.
CAUTION:CAUTION: 101-102-103 now focus on object-oriented (OO) design.101-102-103 now focus on object-oriented (OO) design.
C++ permits an OO approach, but...C++ permits an OO approach, but... Java REQUIRES an OO approach!Java REQUIRES an OO approach!
CPE-101
Interpret or Compile?Interpret or Compile?
BASIC is interpreted:BASIC is interpreted: High-level source code is run by an interpreter on a specific High-level source code is run by an interpreter on a specific
microprocessor.microprocessor. Every time the program is run, it must be re-interpreted.Every time the program is run, it must be re-interpreted.
C and C++ are compiled:C and C++ are compiled: High level source code is run through a compiler.High level source code is run through a compiler. Each compilation is specific to a given microprocessor.Each compilation is specific to a given microprocessor. To run the program, you run the appropriate compiled code.To run the program, you run the appropriate compiled code.
Java is a hybrid:Java is a hybrid: High level source code is run through a compiler to create bytecode.High level source code is run through a compiler to create bytecode. To run the bytecode, you can:To run the bytecode, you can:
Interpret that through a specific Java bytecode interpreter, ORInterpret that through a specific Java bytecode interpreter, OR Compile that into specific machine-code.Compile that into specific machine-code.
CPE-101
Compilers and InterpretersCompilers and Interpreters
We write source code files in the Java language. We write source code files in the Java language. Human beings can read those files.Human beings can read those files.
We then compile the source file down to Java bytecode We then compile the source file down to Java bytecode using a Java compiler:using a Java compiler: javac MyFile.java javac MyFile.java yields yields MyFile.classMyFile.class
Our Java bytecode file can be run in one of two ways:Our Java bytecode file can be run in one of two ways: It can be run on a Java interpreter.It can be run on a Java interpreter. It can be further compiled to native machine code It can be further compiled to native machine code
for a particular machine.for a particular machine.
CPE-101
Executing a Java ProgramExecuting a Java Program
When someone invokes the When someone invokes the java MyFilejava MyFile command... command...
The Java runtime environment first invokes a class loader.The Java runtime environment first invokes a class loader. The class loader loads the bytecodes for all the required The class loader loads the bytecodes for all the required
classes from disk.classes from disk. Once they are loaded, two operations are performed:Once they are loaded, two operations are performed:
A bytecode verifier confirms that all bytecodes are valid.A bytecode verifier confirms that all bytecodes are valid. All bytecodes are checked to see that they do not violate Java’s All bytecodes are checked to see that they do not violate Java’s
security restrictions.security restrictions. The bytecodes are then passed to:The bytecodes are then passed to:
A Java interpreter, A Java interpreter, Or to a Java just-in-time compiler (faster execution).Or to a Java just-in-time compiler (faster execution).
CPE-101
Java Translation and ExecutionJava Translation and Execution
Java sourcecode
Machinecode
Javabytecode
Java programinterpreter
Bytecodecompiler
Javacompiler
Browser Applet Interpreter
CPE-101
Programming Language LevelsProgramming Language Levels
Four levels of programming language:Four levels of programming language: machine languagemachine language assembly languageassembly language high-level languagehigh-level language
procedural (e.g., Algol, Basic, C, Cobol, Fortran, Interlisp, Pascal)procedural (e.g., Algol, Basic, C, Cobol, Fortran, Interlisp, Pascal) functional (e.g., APL, Lisp, Scheme)functional (e.g., APL, Lisp, Scheme) parallel (e.g., High Performance Fortran, Linda)parallel (e.g., High Performance Fortran, Linda) logic (e.g., Duck, Prolog)logic (e.g., Duck, Prolog) combos (e.g., procedural+parallel—Ada or procedural+OO—Loops)combos (e.g., procedural+parallel—Ada or procedural+OO—Loops) object-oriented (e.g., C++, Java, Scheme, Visual Basic)object-oriented (e.g., C++, Java, Scheme, Visual Basic)
fourth-generation languagefourth-generation language
Each type of CPU has its own specific Each type of CPU has its own specific machine languagemachine language The levels beyond that were created to make it easier for The levels beyond that were created to make it easier for
a a human beinghuman being to write programs to write programs
CPE-101
Java Development EnvironmentsJava Development Environments
There are many development environments that develop There are many development environments that develop Java software:Java software: Sun Java Software Development Kit (SDK)Sun Java Software Development Kit (SDK) Borland JBuilderBorland JBuilder MetroWork CodeWarriorMetroWork CodeWarrior Symantec CaféSymantec Café Microsoft Visual J++Microsoft Visual J++
Though the details of these environments differ, the basic Though the details of these environments differ, the basic compilation and execution process is essentially the same.compilation and execution process is essentially the same.
CPE-101
Syntax and SemanticsSyntax and Semantics
The The syntax rulessyntax rules of a language define how we can put of a language define how we can put symbols, reserved words, and identifiers together to make a symbols, reserved words, and identifiers together to make a valid program.valid program.
The The semanticssemantics of a program statement define what that of a program statement define what that statement means (its purpose or role in a program).statement means (its purpose or role in a program).
A program that is syntactically correct is not necessarily A program that is syntactically correct is not necessarily logically (semantically) correct.logically (semantically) correct.
A program will always do what we A program will always do what we toldtold it to do, it to do, not what we not what we meantmeant to tell it to do. to tell it to do.
CPE-101
Java Program StructureJava Program Structure
In the Java programming language:In the Java programming language: A program is made up of one or more A program is made up of one or more classesclasses A class contains one or more A class contains one or more methodsmethods A method contains program A method contains program statementsstatements
These terms will be explored in detail throughout the courseThese terms will be explored in detail throughout the course
A Java application always contains a method called A Java application always contains a method called mainmain (A Java applet does not…)(A Java applet does not…)
CPE-101
Java Program StructureJava Program Structure
public class MyProgram
{
}
// comments about the class
class headerclass header
class bodyclass body
Comments can be added almost anywhereComments can be added almost anywhere
CPE-101
Java Program StructureJava Program Structure
public class MyProgram
{
}
public static void main (String[] args)
{
}
// comments about the class
// comments about the method
method headermethod headermethod bodymethod body
CPE-101
IdentifiersIdentifiers
IdentifiersIdentifiers are the words a are the words a programmerprogrammer uses in a program. uses in a program.
An identifier can be made up of letters, digits, the An identifier can be made up of letters, digits, the underscore character (_), and the dollar sign.underscore character (_), and the dollar sign.
They cannot begin with a digit.They cannot begin with a digit.
Java is Java is case sensitivecase sensitive, therefore, therefore Total Total andand total total are are different identifiers.different identifiers. this makes for many simple to make, hard to find, errorsthis makes for many simple to make, hard to find, errors
CPE-101
IdentifiersIdentifiers
Sometimes we choose identifiers ourselves when writing a Sometimes we choose identifiers ourselves when writing a program.program.
Sometimes we are using another programmer's code, so we Sometimes we are using another programmer's code, so we use the identifiers that they chose (such as use the identifiers that they chose (such as printlnprintln).). does it “come with the language”?does it “come with the language”? no, it is an example of no, it is an example of reuse reuse of code (“libraries”)of code (“libraries”)
Often we use special identifiers called Often we use special identifiers called reserved wordsreserved words that that already have a predefined meaning in the language itself.already have a predefined meaning in the language itself. a reserved word cannot be used in any other way. a reserved word cannot be used in any other way.
CPE-101
Reserved WordsReserved Words
The Java reserved words:The Java reserved words:
abstractbooleanbreakbytebyvaluecasecastcatchcharclassconstcontinue
defaultdodoubleelseextendsfalsefinalfinallyfloatforfuturegeneric
gotoifimplementsimportinnerinstanceofintinterfacelongnativenewnull
operatorouterpackageprivateprotectedpublicrestreturnshortstaticsuperswitch
synchronizedthisthrowthrowstransienttruetryvarvoidvolatilewhile
CPE-101
CommentsComments
Comments in a program are also called Comments in a program are also called inline inline documentationdocumentation
They should be included to explain the purpose of the They should be included to explain the purpose of the program and describe processing stepsprogram and describe processing steps
They do not affect how a program worksThey do not affect how a program works Java comments typically take one of three forms:Java comments typically take one of three forms:
// this comment runs to the end of the line
/* this comment runs to the terminating symbol, even across line breaks */
/** this comment form, which we will not * use yet, is for the javadoc system */
CPE-101
White SpaceWhite Space
Spaces, blank lines, and tabs are collectively called Spaces, blank lines, and tabs are collectively called white space.white space. White space is used to separate words and symbols in a program.White space is used to separate words and symbols in a program. Extra white space is useful to humans, and ignored by machines. Use Extra white space is useful to humans, and ignored by machines. Use
lots of it!!! (And curly braces too.)lots of it!!! (And curly braces too.) A valid Java program can be formatted many different ways.A valid Java program can be formatted many different ways. Programs should be formatted to enhance readability, using consistent Programs should be formatted to enhance readability, using consistent
indentation.indentation. Coding standards are enforced for many projectsCoding standards are enforced for many projects It is quite a serious businessIt is quite a serious business
consider code maintenanceconsider code maintenance
CPE-101
Naming ConventionsNaming Conventions
Give identifiers semantic meaning.Give identifiers semantic meaning. Recall that programmers write identifiers for a purposeRecall that programmers write identifiers for a purpose How does this work with comments in the code?How does this work with comments in the code?
Make identifiers easy to read: Make identifiers easy to read: rr versus versus radiusradius Follow consistent capitaliztion:Follow consistent capitaliztion:
Use lowercase for variable and method names, except for the first letter of Use lowercase for variable and method names, except for the first letter of later words: later words: currentTemperaturecurrentTemperature
All reserved words must be in lower case.All reserved words must be in lower case. Can you use a capitalized “reserved word” any way you Can you use a capitalized “reserved word” any way you like? Try this. Why would you ever want to do it?like? Try this. Why would you ever want to do it?
Use Title Case for class, package, and interface names: Use Title Case for class, package, and interface names: TemperatureConverterTemperatureConverter
Use UPPERCASE for constants, separating words with an underscore: Use UPPERCASE for constants, separating words with an underscore: ABSOLUTEABSOLUTE__ZEROZERO
CPE-101
Three Types of Program ErrorsThree Types of Program Errors
Compile-time errorsCompile-time errors: problems with syntax and other basic : problems with syntax and other basic issues that are found by the compiler.issues that are found by the compiler. If compile-time errors exist, an executable version of the program is If compile-time errors exist, an executable version of the program is
not creatednot created in our case, bytecode is not produced, right?in our case, bytecode is not produced, right?
Run-time errorsRun-time errors: a problem that occurs during program : a problem that occurs during program execution and causes a program to terminate abnormally, execution and causes a program to terminate abnormally, such as trying to divide by zero.such as trying to divide by zero.
Logical ErrorsLogical Errors: a program may run, but still produce : a program may run, but still produce incorrect resultsincorrect results.. What would you suspect “incorrect” means in this case?What would you suspect “incorrect” means in this case?