1. introduction based on java software development, 5 th ed. by lewis &loftus
TRANSCRIPT
1. Introduction1. Introduction
Based on Based on Java Software Development, 5Java Software Development, 5thth Ed. Ed.
By Lewis &LoftusBy Lewis &Loftus
TopicsTopics
Java Programming Language Java Programming Language OverviewOverview
Program DevelopmentProgram Development Object-oriented Programming Object-oriented Programming
OverviewOverview
Java CharacteristicsJava Characteristics Object-oriented LanguageObject-oriented Language
Program consists of a collection of Program consists of a collection of classesclasses Each class contains Each class contains
one or more one or more attributes—data one or more one or more methodsmethods—program —program
statementsstatements Syntax is like C++.Syntax is like C++.
But it is very different from C++ But it is very different from C++ Primitive types have standard sizesPrimitive types have standard sizes Automatic garbage collectionAutomatic garbage collection No pointersNo pointers
Benefits of JavaBenefits of Java PortablePortable
The same source code can be compiled and The same source code can be compiled and executed on any Operating System executed on any Operating System
SecureSecure Designed from the start with security in mind Designed from the start with security in mind
Designed for Network ProgrammingDesigned for Network Programming Makes network-related programming easy Makes network-related programming easy "Network is the computer"--Sun's company motto"Network is the computer"--Sun's company motto
Dynamic ProgramDynamic Program A program can load various modules as needed A program can load various modules as needed
during execution. during execution. InternationalInternational
Java was developed from the start with Java was developed from the start with international use in mind. E.g., Unicode (16 bits) international use in mind. E.g., Unicode (16 bits) encodingencoding
Running a Java ProgramRunning a Java Program
Source Code Bytecode Output
Text Editor Compiler JVM
To Run a Java ProgramTo Run a Java Program
Suppose source code Suppose source code MyProgram.javaMyProgram.java exists in C:\310\.exists in C:\310\.
Compile the source code to Compile the source code to bytecode, which will be named as bytecode, which will be named as MyProgram.classMyProgram.classC:\310> C:\310> javac MyProgram.javajavac MyProgram.java
Run (interpret) the bytecode.Run (interpret) the bytecode.C:\310> C:\310> java MyProgramjava MyProgram
Java Program StructureJava Program Structure
// This is a comment line
class MySample {
}
Class body
Class header
Java Program Structure Java Program Structure (cont.)(cont.)
// This is a comment line
class MySample { public static void main(String args[]) {
}}
Method bodyMethod header
Java Program Structure Java Program Structure (E.g.)(E.g.)
// This is a sample program
class Welcome { // prints a greeting in two lines public static void main(String[] args) { System.out.println(“Hello, Hawaii.”); System.out.println(“Welcome to Kaimuki.”); }
}
RandomTest.javaRandomTest.java// This program generates 10 random numbers.
import java.util.Random;
public class RandomTest { public static void main(String[] args) { Random rand = new Random();
for (int n = 1; n <= 10; n++) { System.out.println(n + ". " + rand.nextFloat ()); } }}
Countdown.javaCountdown.java
// This program counts down numbers from// 10 to 0.
class Countdown { public static void main(String[] args) { for (int i = 10; i >=0; i--) { System.out.println(i + "!"); } System.out.println("Lift Off!"); }}
CommentsComments
Comments do not affect how a Comments do not affect how a program worksprogram works
Java comments can take three forms:Java comments can take three forms:
// This comment runs to end of line.// This comment runs to end of line.
/* This form can be for one line *//* This form can be for one line *//* or it can cover /* or it can cover several lines */ several lines */
/** This is javadoc comment *//** This is javadoc comment */
13
IdentifiersIdentifiers
IdentifiersIdentifiers are the names used in a are the names used in a programprogram
Can be made up of letters, digits, the Can be made up of letters, digits, the underscore character ( _ ), and the underscore character ( _ ), and the dollar signdollar sign
Cannot begin with a digitCannot begin with a digit
Java is Java is case sensitivecase sensitive - - TotalTotal, , totaltotal, , andand TOTALTOTAL are different are different identifiersidentifiers
14
Identifiers (cont.)Identifiers (cont.)
Java convention:Java convention: Lower case for variables: Lower case for variables: name, totalname, total
Upper case for constants: Upper case for constants: MAXIMUMMAXIMUM
Mixed for compound words: Mixed for compound words: lastDayOfWeeklastDayOfWeek
Reserved words (53 in Java) Reserved words (53 in Java) may not be may not be used as identifiers.used as identifiers.
15
Reserved WordsReserved Words
The Java reserved words:The Java reserved words:abstractassertbooleanbreakbytecasecatchcharclassconstcontinuedefaultdodouble
elseenumextendsfalsefinalfinallyfloatforgotoifimplementsimportinstanceofint
interfacelongnativenewnullpackageprivateprotectedpublicreturnshortstaticstrictfpsuper
switchsynchronizedthisthrowthrowstransienttruetryvoidvolatilewhile
16
White SpaceWhite Space Whte spaces:Whte spaces:
spaces, line breaks, and tabs spaces, line breaks, and tabs
used to separate words and symbols in a used to separate words and symbols in a programprogram
Extra white space is ignoredExtra white space is ignored
Enhance program readability with: Enhance program readability with: Blank line to separate major section Blank line to separate major section
Indentation for loop bodyIndentation for loop body
Indentation in If statementsIndentation in If statements
OutlineOutline
Java Programming Language Java Programming Language OverviewOverview
Program DevelopmentProgram Development Object-oriented Programming Object-oriented Programming
OverviewOverview
Programming Language Programming Language LevelsLevels
Machine languageMachine language 0011 1100 1010 1111 1011 0011 1011 1101 11100011 1100 1010 1111 1011 0011 1011 1101 1110
0101 1010 1001 0011 1000 1001 0011 1000 00100101 1010 1001 0011 1000 1001 0011 1000 00100001 1101 0010 0111 1010 1011 0111 1100 01100001 1101 0010 0111 1010 1011 0111 1100 0110
Assembly languageAssembly language ori $8,$0,0x2 ori $8,$0,0x2
ori $9,$0,0x3 ori $9,$0,0x3 addu $10,$8,$9 addu $10,$8,$9
High-level languageHigh-level language sum = num1 + num2sum = num1 + num2
Fourth-generation languageFourth-generation language Report generatorsReport generators
Form generatorsForm generators
Increasing abstraction
Program DevelopmentProgram Development
Steps in Program DevelopmentSteps in Program Development
Writing source codeWriting source code
Compiling source code into machine—Compiling source code into machine—readable formreadable form
Debugging and Testing programDebugging and Testing program
Executing programExecuting program
Typical Programming Typical Programming ProcessProcess
Write Source code in high-level language—Write Source code in high-level language—e.g., Javae.g., Java
Translate source code into machine Translate source code into machine languagelanguage CompilerCompiler translates the entire source code translates the entire source code
into single machine programinto single machine program InterpreterInterpreter translatestranslates and executesand executes the the
source code one line at a time.)source code one line at a time.)
Checking for errors and correcting themChecking for errors and correcting them Execute programExecute program
Each type of CPU requires machine code Each type of CPU requires machine code specific to it (using operating system)specific to it (using operating system)
Basic Program Basic Program DevelopmentDevelopment
errors
errors
Edit andsave program
Compile program
Execute program andevaluate results
©2007 Pearson Addison Wesley
Java Programming Java Programming ProcessProcess
Write source code in JavaWrite source code in Java Translate source code into a Translate source code into a
bytecodebytecode (machine laguage). (machine laguage). Execute the bytecode by interpretor Execute the bytecode by interpretor
(Java Virtual Machine)(Java Virtual Machine) Each CPU runs the Virtual MachineEach CPU runs the Virtual Machine Which executes the bytecodeWhich executes the bytecode
Java EnvironmentJava Environment
The Java environment consists of the The Java environment consists of the following elements.following elements.
Java Programming Language Java Programming Language grammar for writing application programs, grammar for writing application programs,
applets, JavaBeans components, etc.applets, JavaBeans components, etc. Java Virtual Machine (JVM) Java Virtual Machine (JVM)
software for executing Java binary programs, software for executing Java binary programs, called byte codecalled byte code
Java Platform (Java Standard Library, Java Java Platform (Java Standard Library, Java API) API) set of predefined classesset of predefined classes
Java Virtual MachineJava Virtual Machine Source code is compiled into a binary file Source code is compiled into a binary file
known as a bytecode. known as a bytecode. Bytecode is then interpreted by the Bytecode is then interpreted by the Java Java
Virtual MachineVirtual Machine, which sits atop an , which sits atop an operating system--Windows, MacOS, operating system--Windows, MacOS, Lunux. Lunux.
Since the bytecode does not need to know Since the bytecode does not need to know the kind of OS on which it is being the kind of OS on which it is being executed--the JVM is tailored to particular executed--the JVM is tailored to particular OS--a Java code is highly portable from OS--a Java code is highly portable from one type of computer system to another.one type of computer system to another.
25
Java TranslationJava Translation
Java sourcecode
Machinecode
Javabytecode
Bytecodeinterpreter
Bytecodecompiler
Javacompiler
©2007 Pearson Addison Wesley
TerminologyTerminology SyntaxSyntax
Rules of language (grammar)Rules of language (grammar) d = a(b + c); -- syntax errord = a(b + c); -- syntax error
SemanticsSemantics Meaning of the languageMeaning of the language speed = distance * time;speed = distance * time;
--syntactically correct, semantically wrong--syntactically correct, semantically wrong ErrorsErrors
Compile-time error (e.g., syntax error)Compile-time error (e.g., syntax error) Run-time error (e.g., dividing by 0)Run-time error (e.g., dividing by 0) Logic error (program runs, but produces wrong Logic error (program runs, but produces wrong
result)result)
OutlineOutline
Java Programming Language Java Programming Language OverviewOverview
Program DevelopmentProgram Development Object-oriented Programming Object-oriented Programming
OverviewOverview
Problem SolvingProblem Solving
Steps in problem solving:Steps in problem solving:
Understand the problemUnderstand the problem Design a solutionDesign a solution Consider alternatives and refine the solutionConsider alternatives and refine the solution Implement the solutionImplement the solution Test the solutionTest the solution
These steps are not linear—they overlap These steps are not linear—they overlap and repeatand repeat
Problem Solving (cont.)Problem Solving (cont.)
The key strategy to solve a complex The key strategy to solve a complex problem is to break it down into problem is to break it down into manageable pieces and solve each manageable pieces and solve each piece—piece—dividedivide and conquerand conquer method. method.
Object-orientedObject-oriented approach sees a approach sees a program in terms of a collection of program in terms of a collection of “objects” interacting with each other.“objects” interacting with each other.
With Java, objects and classes are the With Java, objects and classes are the basic units of a programbasic units of a program
Objects and ClassesObjects and Classes
An OO program consists of a collection of An OO program consists of a collection of objects interacting with each other.objects interacting with each other.
Suppose you are writing a game program Suppose you are writing a game program that involves several dogs, cats, and cars. that involves several dogs, cats, and cars. (Use your imagination.)(Use your imagination.)
Here are some dog objects: Here are some dog objects: Fido—a big brown bulldogFido—a big brown bulldog Lassie—a tall collieLassie—a tall collie Taro—a small, white akitaTaro—a small, white akita
ObjectsObjects
Attributes: name = Fido breed = bulldog color = brown weight = 30 kg height = 50 cmOperations: bark() display()
Attributes: name = Lassie breed = collie color = brow weight = 25 kg height = 70 cmOperations bark() display()
Attributes: name = Taro breed = akita color = white weight = 10kg height = 30 cmOperations bark() display()
Dog1
Dog2Dog3
ClassClass A class is an A class is an abstractionabstraction of the objects of of the objects of
the same type. Fido, Lassie, and Taro are the same type. Fido, Lassie, and Taro are all all instancesinstances of the of the DogDog class. class.
Each objects has a number of Each objects has a number of attributesattributes (with different values) and (with different values) and operationsoperations (same methods). (same methods).
A class is A class is a template for creating (specifying) objects of a a template for creating (specifying) objects of a
particular type.particular type. like blueprint for creating objects of a like blueprint for creating objects of a
particular typeparticular type
Class (cont.)Class (cont.)
A class is composed ofA class is composed of Class NameClass Name AttributesAttributes Operations (methods)Operations (methods)
Once a class is defined, objects can Once a class is defined, objects can be created (instantiated) from it.be created (instantiated) from it.
Class DiagramClass Diagram
Dog
breedcolorweightheight
Bark()display()
Class name
Attributes
Operations
Car
makeengineSizecolormaxSpeed
Start()accelerate()stop()display()
Class (summary)Class (summary) A class defines an object.A class defines an object.
A class is the blueprint, or template, of an objectA class is the blueprint, or template, of an object
A class represents a concept, and an object A class represents a concept, and an object represents the embodiment of that conceptrepresents the embodiment of that concept
Multiple objects can be created from the same Multiple objects can be created from the same classclass
The class uses methods to define the behaviors of The class uses methods to define the behaviors of the objectthe object
The class that contains the The class that contains the mainmain method of a Java method of a Java program represents the entire programprogram represents the entire program
Classe and ObjectClasse and Object
Bank Account
A class(the concept)
John’s Bank AccountBalance: $5,257
An object(the realization)
Bill’s Bank AccountBalance: $1,245,069
Mary’s Bank AccountBalance: $16,833
Multiple objectsfrom the same class
©2007 Pearson Addison Wesley
InheritanceInheritance One class can be used to derive another via One class can be used to derive another via
inheritanceinheritance
Classes can be organized into hierarchiesClasses can be organized into hierarchies
Bank Account
Account
Charge Account
Savings Account
Checking Account
©2007 Pearson Addison Wesley
Inheritance (2)Inheritance (2) One class can be used to derive another via One class can be used to derive another via
inheritanceinheritance
Classes can be organized into hierarchiesClasses can be organized into hierarchies
Full-time
Employee
Part-time ]
Hourly-wage
Annual-salary
©2007 Pearson Addison Wesley
PracticePractice
Specify some relevant attributes and Specify some relevant attributes and operations for the following classes.operations for the following classes. Bank AccountBank Account BookBook Browser windowBrowser window Circle (geometric figure)Circle (geometric figure) Rectangle (geometric figure)Rectangle (geometric figure)