0% found this document useful (0 votes)
10 views81 pages

L01 Programming & Introduction To Java

The document provides an introduction to computer programming in Java, covering topics such as algorithms, problem-solving, and the basics of Java programming. It explains the process of programming, including coding, testing, and maintenance, as well as the features and applications of Java. Additionally, it outlines the Java development environment phases from creating programs to execution.

Uploaded by

yihitot430
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views81 pages

L01 Programming & Introduction To Java

The document provides an introduction to computer programming in Java, covering topics such as algorithms, problem-solving, and the basics of Java programming. It explains the process of programming, including coding, testing, and maintenance, as well as the features and applications of Java. Additionally, it outlines the Java development environment phases from creating programs to execution.

Uploaded by

yihitot430
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CS1701T: Computer Programming in Java

1st Semester 2025

Lecture 1
Programming & Introduction to Java

Source: Dr. Malak AlGabri and Dr. Areej Althobiti slides


Modification: Dr Majdah Alsharif
1
Topics covered:
• The concept of algorithms for solving simple problems

• Definition of programming, programs and programming languages

• Introduction to Java programming language

• Testing, and debugging

• Documentation and program style

• Techniques of decomposition and abstraction

2
What Is Programming?

• Programming is a process of problem solving.

• We could think of programming as the process of breaking down a large,


complex task into smaller and smaller subtasks.

• The process continues until the subtasks are simple enough to be


performed with the electronic circuits provided by the hardware.

• The person who writes a program is called the programmer.


• The person who interacts with the program is called the user.

3
Problem Solving & Algorithm

• Problem solving is the process of identifying a problem, developing an


algorithm, and eventually implementing a computer program

Analyzing Developing
Coding Testing
Problem Algorithm

• An algorithm is a set of finite, sequential, and unambiguous steps


usually described in natural language to solve a given problem.

• Two most common methods to represent algorithms are:


 Flowcharts is a graphical representation of an algorithm

 Pseudocode is a description of the instructions that human could


understand and so the computer could execute later on 4
Problem Solving & Algorithm (cont.)

Flowchart Symbols

5
Problem Solving & Algorithm (cont.)

Problem Solving Steps:


Step1: Analyze the problem
• Understand the overall problem
• Define problem requirements
 Does program require user interaction? If yes, What is the Input?
 What is the expected Output?
• Design steps (algorithm) to solve the problem

6
Problem Solving & Algorithm (cont.)
Step2: Implement the algorithm
• Implement the algorithm in code (coding)
• Verify that the algorithm works (testing)

Step3: Maintenance
• Use and modify the program if the problem domain changes. (any
changes required)

• Note: If the problem is complex, divide it into sub problems and then
analyze each sub-problem as above

7
Problem Solving & Algorithm (cont.)
Example 1:
• Write a Pseudocode and draw a flowchart to convert the length from
feet to centimeter.

Pseudocode:
• Input the length in feet (Lft)
• Calculate the length in cm (Lcm) by multiplying LFT with 30
• Print length in cm (Lcm)

8
Problem Solving & Algorithm (cont.)
Example 1 Flowchart:

9
Problem Solving & Algorithm (cont.)
Example 2:
• Write a Pseudocode and draw a flowchart to determine a student’s final
grade and indicate whether it is passing or failing. The final grade is
calculated as the average of four marks

Pseudocode:
• Input a set of 4 marks
• Calculate their average by summing and dividing by 4
• if average is below 50, Print “FAIL”
Else Print “PASS”

10
Problem Solving & Algorithm (cont.)
Example 2 Flowchart:
START

Input
M1,M2,M3,M4

GRADE(M1+M2+M3+M4)/4

N IS Y
GRADE<5
0

PRINT PRINT
“PASS” “FAIL”

STOP

11
Programming Paradigms
• Procedural/Functional paradigm:
 in which programs consist of a collection of procedures and functions that
operate on data.

 Example: Fortran, Pascal, and C

• The object-oriented paradigm:


 in which programs are viewed instead as a collection of “objects” for
which the data and the operations acting on that data are encapsulated
into integrated units.

 Example: Smalltalk, C++, and Java.

12
Programs
• A program is a set of instructions for a computer to follow that directs the
computer to do the tasks you want it to do and produce the results you
want.

• A program is like a recipe. It contains a list of variables (called ingredients)


and a list of statements (called directions) that tell the computer what to
do with the variables.

• Following the instructions is called running or executing the program

• We use programs almost daily (email, word processors, video games, bank
ATMs, etc.).

13
Programs (Cont.)
• We use programs almost daily (email, word processors, video games, bank
ATMs, etc.).

• Programmers tell a computer what to do through programs. Without


programs, a computer is an empty machine.

• Computers do not understand human languages, so we need to use


computer languages to communicate with them.

• Programs are written using programming languages.

14
Running a Program
• Normally, a computer receives two kinds of input:
• The program
• The data needed by the program.

• The output is the result(s) produced by following the instructions in the


program.

15
Programming Languages
• Programming languages are a set of instructions written in a way that
a computer could understand

• Why do we need programming languages?


• All computer components: Central Processing Unit(CPU), memory,
and Input/Output (I/O) understands a machine code called a
binary.
• Binary is a long string of 0’s and 1’s that human cannot
understand!
• So how can we make the computer to perform a certain task?
Programming languages helps us in doing so by providing an intermediate solution
between the human and the machine

• Each language has a unique set of keywords (words that it


understands) and a special syntax for organizing program instructions.
16
Syntax and Semantics of programming
languages
• Syntax and Semantics provide a language's definition.
• The grammar rules for a programming language are called
the syntax of the language (detected by the compiler). Different
languages have different syntax.
 e.g., while statement in java
• The interpretation or the meaning of the statements is
called the semantic of the language.
 e.g., Array index out of range
int[] v = new int[10];
v[10] = 100; // 10 is not a legal index for an array of 10 elements
 e.g., Use of a non-initialized variable
int i;
i++; // the variable i is not initialized

17
Basic instructions in programming
languages
• input: Get data from the keyboard, a file, a sensor, or some other
device.

• output: Display data on the screen or send data to a file or other
device.

• math: Perform basic mathematical operations like addition and


division.

• decision: Check for certain conditions and execute the appropriate


code.

• repetition: Perform an action repeatedly, usually with some variation.

18
Programming Languages Categories
• Low-level languages (machine Assembly
High-level
language):
they are close to the machine
language e.g. assembly language

• High-level languages:
they are closer to the programmers'
language (more friendly!) e.g. Java

19
Levels of Programming Languages

• High-level languages are relatively easy to


Natural Language
use (i.e., more flexibility, easier to be
Implemented, maintained)
Very High-Level
Language
• Unfortunately, computer hardware does
(e.g., Java, C++, C#)
not understand high-level languages!,
Therefore, a high-level language program
High Level Language
must be translated into a low-level
(e.g., Fortran, Cobol)
language.
Assembly Language
(In[Link] Sun
Sparc)

Speed Machine Language


(e.g., 01001110000)
20
Choosing A Language

Depends on your tasks:


• Satellite communication (speed)  Assembly

• Education Basic, Pascal

• Business  Cobol

• Web development JavaScript, JSP, .NET

• Scientific calculation Fortran, Matlab

• Embedded and Operating Systems C

• Enterprise applications  Java

21
Translating/Converting High-level to Low-
level
• A source program must be translated into a machine code.

• An application program called a translator which transforms code


from High Level Language to Low Level Language, making it
machine understandable code.

• Compilers and interpreters are simply language translators in


computer programming.

• The program is run by loading machine code into main memory. The
processor directly executes these machine language instructions

22
Compilers

• A compiler is a program that takes a high-level language program and


translates the entire program into machine code all at one time
• All instructions are compiled before any are executed by the CPU
• The Java compiler (javac) translates Java source code ([Link]) into a
special representation called bytecode (object program)
• When a Java program is translated into bytecodes, the bytecodes are
exactly the same no matter what computer system is used
• Compilation process occurs only once, and the resulting object program
could be run as often as needed without re-compiling the source
program

23
Interpreters
• An interpreter reads through a source program written in a high-level
language and performs the instructions that the source program asks
for one by one.

• Once a given instruction has been translated and executed, the next
one then will follow, and so on

• The Java Virtual Machine (JVM) uses an interpreter, to translate


bytecode into machine language and executes it

24
Java History
• Java is a high-level object-oriented programming
language developed by James Gosling at Sun
Microsystems in the early 1990s.
• He was unhappy using c++ programming language so
he developed java.
• Java Old name was “Oak”
• 1995 “Oak” was renamed as Java as a core
components of Sun microsystems java platform
• Java is a consolidation language, designed to absorb
the strengths of earlier languages and ignore their
weakness
• According to sun, 3 billions devices run java.

25
Java Features
• Simple
 Java syntax is based on C++ (greatly simplified and improved).
 Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
 There is no need to remove unreferenced objects because there is an
Automatic Garbage Collection in Java.

• Platform-Independent (portable)
 Write once run anywhere
 Java is completely portable; the same Java code will run identically on
different platforms, regardless of hardware compatibility or operating
systems.

• Object oriented
 OOP is a popular programming approach that is replacing traditional
procedural programming which offers great flexibility, modularity, clarity,
and reusability
26
 All coding and data reside within objects and classes
Java Features (Cont.)
• Robust and secure
 Exception handling built-in strong type checking
 automatic garbage collection so all memory corruptions or unauthorized
memory accesses are impossible
 strong memory management (no-pointers).
 Programs run inside the virtual machine sandbox

• Compiled and interpreted


• Code is complied to bytecode that are interpreted by a JVM

• Distributed
 Creating applications on networks.
 Multiple programmers can work together on a single project from multiple
remote locations and share data and programs.

27
Java Features (Cont.)
• Multithreaded
 It allows to handle multiple tasks simultaneously (run multiple threads )

• Architecture-Neutral
 no implementation dependent features e.g. size of primitive types is fixed.

• High-performance
 The new JVM uses the technology known as just-in-time (JIT) compilation.
 With JIT complier the interpreted code gives almost the native code speed.

28
Java Applications
• Stand alone applications
 Also known as desktop applications
 They are traditional software i.e., we need to install to every machine
 Examples: Acrobat reader, Media player, Antivirus, etc.
• Web applications
 These applications that runs on the server side and creates a dynamic pages.
 Technologies such as JSP, Servlet, spring, etc. are used for creating web applications
in java.
 Example: [Link], [Link] (student information system (SIS))
• Enterprise applications
 An application that is distributed in nature, such as Banking applications.
 It has advantages of high-level security, load balancing, and clustering.
• Mobile applications
 An application which is created for mobile devices
 Currently, Android and java Me are used for creating mobile applications.
• Other applications such as robotics, games, etc.
29
[Link]
Java Development Environment Phases

30
[Link]
Java Development Environment Phases (Cont.)
• Step1: Creating and Editing Programs
 This step involves using an editor to type a Java program (source code), then save it
on a secondary storage device, such as hard drive.

 Well-known editors: Notepad on Windows and TestEdit on OS X

 Integrated development environments (IDEs) provide tools that support the


software development process, such as editors, debuggers for locating logic errors
(errors that cause programs to execute incorrectly) and more.

 Popular Java IDEs:


 Eclipse ([Link] )
 NetBeans ([Link])
 IntelliJ IDEA ([Link])
 VSCode ([Link]) -- Not just Java!

 All Java source code files are ending with the .java extension.

31
Java Development Environment Phases (Cont.)
• Step2: Compiling a Java Program into Byte-codes
 The Java compiler does not translate a Java program into machine language for a
particular computer.

 Instead, it translates a Java program into byte-code.

 Byte-code:
 is the machine language for a hypothetical computer (or interpreter) called the Java
Virtual Machine.
 The byte-code file has a .class file extension
 byte-code represents the tasks to execute in the execution phase
 Bytecodes are executed by the Java Virtual Machine (JVM)—a part of the JDK and the
foundation of the Java platform
 Bytecodes are platform independent
 They do not depend on a particular hardware platform
 Bytecodes are portable
 The same bytecodes can execute on any platform containing a JVM that understands the
version of Java in which the bytecodes were compiled
 Bytecode can be sent over the Internet and used anywhere in the world. This makes Java
suitable for Internet applications. 32
Java Development Environment Phases (Cont.)
• Step3: Loading a Program into Memory
 The Java Virtual Machine (JVM) places the program in memory to execute it—this
process is known as loading

 The JVM’s class loader (also called the linker ) takes the .class files containing the
program’s byte-codes and transfers them to main memory.

 A class loader automatically connects the classes together.

33
Java Development Environment Phases (Cont.)
• Step 4: Bytecode Verification
 As the classes are loaded, the bytecode verifier checks their bytecodes to ensures
that they’re valid and don’t violate Java’s security restrictions

 Java enforces strong security to make sure that Java programs arriving over the
network do not damage your files or your system (as computer viruses and worms
might)

34
Java Development Environment Phases (Cont.)
• Step5: Interpreting and Execution
 The Java Virtual Machine (JVM) translates each byte-code instruction
and executes the resulting machine-language instructions before translating the
next byte-code instruction.

 Most Java programs today are executed using a Just-In-Time or JIT compiler. JIT
compilers interact with the Java Virtual Machine (JVM) at run time and compile
suitable bytecode sequences into native machine code that can be sent directly to a
computer's processor (CPU).

35
Recap
• Java code is usually compiled into platform independent bytecode (class
files).

• The JVM is able to load the class files and execute the java bytecode via
the java interpreter.

• Even though this bytecode is usually interpreted, it might also be


compiled into native machine code using the JVM’s Just-In-Time (JIT).

• Unlike the normal compiler, the JIT compiler compiles the code
(bytecode) only when required.

• So, JVM provides a platform-independent way of executing Java


bytecode. It is a keystone of the write-once run any ware value of java
programs. 36
Core Concepts in Java

37
Core Concepts in Java (Cont.)

• Java Runtime Environment (JRE)


 It Includes the following:
 The Java Virtual Machine (JVM) with a Jit compiler
 Java class libraries

 It is used to:
 read bytecode
 run the same bytecode on any machine with a JVM (run any java program)

38
Core Concepts in Java (Cont.)

• Java Development Kit (JDK)


 It Includes the following:
 JRE
 Java Compiler
 Other tools (include Java libraries, Java source compilers,
Java debuggers, bundling and deployment tools)

 It is used to simply compile bytecode (.java -> .class)

39
Recap

Compiling and Running a Java Program (Overall Picture)

40
Programming Basics

41
41

Reserved Keywords
• Reserved words or keywords are words that have a specific
meaning to the compiler and cannot be used for other purposes in
the program. Reserved words are always spelled withall lowercase
letters.

• For example, when the compiler sees the word class, it


understands that the word after class is the name for the class.

• We must use reserved words only for their intended purpose.


For example, we can't use the word class for any other
purpose than defining a class
42

Reserved Keywords (Cont.)

abstract else interface switch


assert enum long synchronized
boolean extends native this
break false new throw
byte final null throws
case finally package transient
catch float private true
char for protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instanceof strictfp
double int super
Compiling and Running a Java Program or
Class

• A Java program consists of


one or more classes,
which must be compiled
before running the
program.

• Each class should be in a


separate file.

44
Compiling and Running a Java Program or
Class (Cont.)
• The name of the file should be the same as the name of the class.

• The class will contain the statement below (only ONE class must include the
main method)

public static void main(String[] args)

45
Testing and Debugging

• The best way to write a correct program is to carefully design the


necessary objects and the algorithms for the objects’ methods.

• Then you carefully translate everything into a programming language


such as Java.

• So, to eliminate errors is to avoid them in the first place

• Test your program with appropriate test cases (some where the answer
is known), discover and fix any errors, then retest.

46
Programming Errors
• A mistake in a program is called a bug.

• The process of eliminating errors is called debugging.

• Three kinds of errors:


 Syntax errors
 Runtime errors
 Logic errors

47
Programming Errors (Cont.)
• Syntax Errors:
 The syntax of a programming language is the set of grammatical rules for
the correct way to write a program.

 Thus, syntax errors are the grammatical mistakes in a program

 The compiler catches syntax errors and prints an error message.

 Example: missing semicolon.

48
Programming Errors (Cont.)
• Runtime Errors:
 Errors that are detected when your program is running, but not during
compilation

 When the computer detects an error, it terminates the program and prints
an error message.

 The error message might not be easy to understand, but at least you will
know that something is wrong!

 Example: attempting to divide by 0.

49
Programming Errors (Cont.)
• Logic Errors:
 Errors that are not detected during compilation or while running, but which
cause the program to produce incorrect results.

 Logic errors will not give you any error messages. For this reason, logic
errors are the hardest kind of error to locate.

 Example: an attempt to calculate a Fahrenheit temperature from a Celsius


temperature by multiplying by 9/5 and adding 23 instead of 32

50
Basic Java Program Structure
• There are 5 components that we usually include in a Java program,
which are:

[ Documentation Statement(s) ]
[ Package Statement ]
[ Import Statement(s) ]
public class className {
public static void main(String[] args) {

[ Body of Main Function ]


}
}

51
Basic Java Program Structure (Cont.)
• Documentation Statement(s):
 It includes "comments" lines that we use to describe the whole idea
behind the program and its methods

 The compiler ignores these comments during the time of execution.

 It helps other programmers to easily understand your code!

52
Basic Java Program Structure (Cont.)
• Documentation Statement(s):
 There are three types of comments that Java supports:-

Single line Comment Multi-line Comment Javadoc


Comment
• begins with // • A multi-lines comment can -
begin with /* and end with
• Everything after these */
symbols and to the end of
the line is treated as a • Everything between these
comment and is ignored by symbols is treated as a
the compiler. comment and is ignored by
the compiler.
• Example:
double radius; //in cm • Example:
/*
This program should only
be used on math problems
*/
53
Basic Java Program Structure (Cont.)
• Package Statement(s):
 A package is a library or container of a group of related classes (think of it
as a folder in a file directory) that could be user-defined or have been
defined by java already (built-in).

 They are optional and used to declare classes in a collection called package

 Only one package statement is allowed in a program

 Package statements must be at the beginning of the code before any class
or interface declaration!

 Syntax: package name;

 Example: package people; Note, this statement declares that all the
classes and interfaces defined in this source
file are a part of the people package
54
Basic Java Program Structure (Cont.)
• Import Statement(s):
 They are used to refer to set of classes that are located in other packages

 Always write the import statements after the package statement and before
the class declaration.

 Syntax: import [Link];

 Example: import [Link]; //imports the date class

55
Basic Java Program Structure (Cont.)
• Class Definition(s):
 A class is a collection of variables and methods that operate on the
attributes or fields.

 Syntax:

 the public keyword means this class is accessible by any other classes

 The curly brackets are used to make sure that the statements belong to
one class
56
Basic Java Program Structure (Cont.)
• Class Definition(s):
 Class declaration (header)
 Every Java program consists of at least one class that you define
 class keyword introduces a class declaration and is immediately followed by the
class name
 Java class declaration normally contain one or more methods.
 One of these classes must have the main method

 Class name
 By convention, begin with a capital letter
 Camel Case is a style used to capitalizing the initial letter of each word and omitting
spaces (e.g., SampleClassName).
 A class name is an identifier—a series of characters consisting of letters, digits,
underscores (_) and dollar signs ($) that does not begin with a digit and does not
contain spaces
 Java is case sensitive—uppercase and lowercase letters are distinct

57
Basic Java Program Structure (Cont.)
• Main Method:
 The main method is the place where the program execution starts. Meaning the
computer follows the order specified by the Java statements.

 The main method is an essential part of any program in Java and where the JVM
starts running the program

 The main method is declared inside the class definition

 Where:
 public means that this method can be used outside of this class
 static means that there is no need to create an object to access this a method
 void means that this method does not return any value
 String[] args is an array named as args where each element is a string. We use it
to pass the input to the program when we run the Java code through a console

 Declaring main as static allows the JVM to invoke main without creating an
instance of the class 58
Basic Java Program Structure (Cont.)
• Main Method:
 Syntax:

59
Basic Java Program Structure (Cont.)
• Block:
 It is a pair of curly braces in a program forms a block that groups components
of a program

 Examples: Class block, method block, statement block, ...

 A left brace { begins the body of every class declaration

 A corresponding right brace } must end each class declaration

 It is a syntax error if braces do not occur in the matching pairs

 Example:

60
Basic Java Program Structure (Cont.)
• Block:
 You may use next-line or end-of-line style for braces

 You should stick with one style in the whole code

61
Basic Java Program Structure (Cont.)
• Block:
 Which code do you think it is more readable?

62
Basic Java Program Structure (Cont.)
• Statement:
 Is a command for the computer to do something.

 MOST statements in Java should be followed by a semicolon ( ; )

 Methods are built out of statements.

 The statements in a method are placed between braces { and }

 There are several types of statements in Java. For example, declaration,


assignment, control, and loop statements.

63
Basic Java Program Structure (Cont.)
• Statement:
 Example Explanation:

class object method

statement
 Instructs the computer to display a string of characters contained between the
double quotation marks on the screen

 White-space characters in strings are not ignored by the compiler

 The string in the parentheses is the argument to the method

 Positions the output cursor at the beginning of the next line on the screen
(command window)
64
Basic Java Program Structure (Cont.)
• Statement:
 Example Explanation:
 Strings cannot span multiple lines of code

65
A First Java Application

66
A First Java Application (Cont.)

Sample
screen
output

67
A First Java Application (Cont.)
• Tracing the Program:

68
A First Java Application (Cont.)
• Tracing the Program:

69
A First Java Application (Cont.)
• Tracing the Program:

70
Recap
• Proper Indentation and Spacing:
 Use blank lines to separate segments of the code .

 Use space characters and code indentations to enhance program readability

 Write each statement in a separate line , allowing end of line comment.

 For example:
[Link]("Hello World!"); // print a string

71
Recap (Cont.)
• Appropriate Comments:
 Starts your program with a comment that states the purpose of the program,
the author, time and date of the last program modifications

 Write a comment before each class, documenting the purpose of the class

 Write a comment before each method, documenting the purpose of the


method

 Write an end of line (single line) comment, documenting the purpose of the
statement

72
Recap (Cont.)
• In every Java source file, you might see the following 5 components:

//comments
package name;

import className;

public class className{


//attributes
//methods
public static void main (String[]args){
//statements
}
}

73
Techniques of Decomposition and
Abstraction

74
Decomposition
• Decomposition is breaking a complex problem down into smaller
problems and solving each one individually

• Decompose the problem so that:


 Each subproblem is at the same level of detail
 Each subproblem can be solved independently
 The solutions to the subproblems can be combined to solve the original
problem

75
Decomposition (Cont.)
• Advantages
 Different people can work on different subproblems
 Parallelization may be possible
 Maintenance is easier
• Disadvantages
 Solutions to the subproblems might not combine to solve the original
problem
 Poorly understood problems are hard to decompose

• Decomposition doesn’t always work (e.g. writing a play)

• Decomposition isn’t always possible


 for very complex problems (e.g. Managing the economy)
 for impossible problems (e.g. Turning water into wine)
 for atomic problems (e.g. Adding 1 and 1)
76
Decomposition (Cont.)
• Step 1: Identify components
 a good decomposition minimizes dependencies between components
 coupling - a measure of component connectivity
 cohesion - a measure of how well the contents of a component go together

 Information hiding
 having modules keep their data private
 provide limited access procedures

• Step 2: Model the components


 At the design Level
 Structure charts, object diagrams, dataflow diagrams

 At the coding level


 procedure declarations, procedure specifications

77
Abstraction
• Abstraction is the process of removing unnecessary details so that only
the important points remain
• In programming, abstraction is the process of naming compound objects
and dealing with them as single entities

• It allows you to:


 ignore inconvenient detail
 simplify many types of analysis

• Abstraction can help with decomposition (e.g. to manage the economy, try
focusing on some abstracted features such as inflation)
• Abstraction doesn’t solve problems, but it allows us to simplify them

• Abstraction Forms: Abstraction by Parameterization, Abstraction by


Specification 78
Abstraction (Cont.)
1) Abstraction by Parameterization
 Example: computes the difference of the squares of two specific variables, x
and y.

 The abstraction:
int squares (int x, int y) {
return(x * x - y * y);
}
 describes a set of computations which act on any two (integer) variables to compute
the difference of their squares.
 Note: locally the variables are called x and y for convenience

 The code below uses the abstraction squares on two specific variables
(‘big’ and ‘small’)
result = squares(big, small);

79
Abstraction (Cont.)
2) Abstraction by Specification
 Abstraction by parameterization allows us to express computations but does
not tell us about the intention of those computations

 Abstraction by Specification tells the client of an abstraction what he/she can


expect it to do

 It is a contract between client and implementer:


 Client will only rely on behavior described by specification
 Implementer will provide an implementation that satisfies the specification

80
Abstraction (Cont.)
• Unfortunately only abstraction by parameterization is built into our
programming languages as function (procedure) definitions
• We can overcome this using comments

int strlen (char s[]) {


/* precondition: s must contain a character array,
delimited by the null character;
postcondition: returns the length of s as an integer;
*/
int length = 0;
while (s[length])
length++;
return(length); }

81

You might also like