Chapter 1 Introduction To Computers, Programs, and Java
Chapter 1 Introduction To Computers, Programs, and Java
0
Pz Pz
cadet
1,4 30521
What is a Computer?
➢A Computer systems consist of hardware and software.
➢ Hardware includes the tangible parts of computer systems.
➢ Software includes programs
0
CPU
➢The central processing unit (CPU) is the brain of a computer. It
retrieves instructions from memory and executes them.
➢The CPU speed is measured in hertz (MHz), with 1 megahertz
equaling 1 million pulses per second.
➢It consists of Arithmetic and logic unit (ALU), control unit (CU)
and registers
0
Memory
➢Memory is to store data and program instructions for CPU to
execute.
➢A program and its data must be brought to memory before they
can be executed.
0
How Data is Stored?
➢Data of various kinds, such as
numbers, characters, and strings, are
encoded as a series of bits (zeros and
ones).
➢A bit is a digit with a value of either
0 or 1.
➢A byte consists of 8 bits.
➢Each byte in main memory resides
at a numbered location called its
address.
➢No two data can share or split a
same byte.
➢A byte is the minimum storage unit.
0
Programs
➢Computer programs, known as software, are instructions
to the computer.
➢You tell a computer what to do through programs.
Without programs, a computer is an empty machine.
➢Computers do not understand human languages, so you
need to use computer languages to communicate with
them.
➢Programs are written using programming languages.
0
Programming Languages
Machine Language Assembly Language High-Level Language
0
Programming Languages
Machine Language Assembly Language High-Level Language
0
Programming Languages
Machine Language Assembly Language High-Level Language
0
Interpreting/Compiling Source Code
➢A program written in a high-level language is
called a source program or source code.
➢Because a computer cannot understand a source
program, a source program must be translated into
machine code for execution.
➢The translation can be done using another
programming tool called an interpreter or a
compiler.
0
o web.TT
IWiwipwa
it Interpreting Source Code
An interpreter reads one statement from the source
code, translates it to the machine code or virtual
machine code, and then executes it right away, as
shown in the following figure. Note that a statement
from the source code may be translated into several
machine instructions. g
0
one ix brains
Compiling Source Code
A compiler translates the entire source code into a
machine-code file, and the machine-code file is then
executed, as shown in the following figure.
0
Operating Systems
The operating system (OS) is
a program that manages and
controls a computer’s
activities. The popular
operating systems for general-
purpose computers are
Microsoft Windows, Mac OS,
and Linux. Application
programs, such as a Web
browser or a word processor,
cannot run unless an
operating system is installed
and running on the computer.
0
Why Java?
The answer is that Java enables users to develop and
deploy applications on the Internet for servers, desktop
computers, and small hand-held devices. The future of
50.1 imam
computing is being profoundly influenced by the Internet,
and Java promises to remain a big part of that future. Java
is the Internet programming language.
0
Java, Web, and Beyond
F Java can be used to develop Web
applications.
F Java can be used to develop applications
running from a browser.
F Java can also be used to develop applications
for hand-held devices
F Java can be used to develop applications
for Web servers.
0
Characteristics of Java
saw
F Java Is Simple Java is partially modeled on C++, but greatly
simplified and improved. Some people refer to
F Java Is Object-Oriented Java as "C++--" because it is like C++ but
F Java Is Distributed with more functionality and fewer negative
aspects. I bi 6 É
F Java Is Interpreted
F Java Is Robust
F Java Is Secure
F Java Is Architecture-Neutral
F Java Is Portable
F Java's Performance
F Java Is Multithreaded
F Java Is Dynamic
0
Characteristics of Java translate
0
Characteristics of Java translate
0
Characteristics of Java
F Java Is Simple You need an interpreter to run Java
programs. The programs are compiled into
F Java Is Object-Oriented the Java Virtual Machine code called
F Java Is Distributed bytecode. The bytecode is machine-
independent and can run on any machine
F Java Is Interpreted that has a Java interpreter, which is part of
F Java Is Robust the Java Virtual Machine (JVM).
F Java Is Secure
F Java Is Architecture-Neutral
F Java Is Portable
F Java's Performance
F Java Is Multithreaded
F Java Is Dynamic
0
Characteristics of Java
F Java Is Simple Java compilers can detect many problems
that would first show up at execution time
F Java Is Object-Oriented in other languages.
F Java Is Distributed
Java has eliminated certain types of error-
F Java Is Interpreted prone programming constructs found in
as other languages.
F Java Is Robust
F Java Is Secure Java has a runtime exception-handling
F Java Is Architecture-Neutral feature to provide programming support
for robustness.
F Java Is Portable
F Java's Performance
F Java Is Multithreaded
F Java Is Dynamic
0
Characteristics of Java
F Java Is Simple
F Java Is Object-Oriented
F Java Is Distributed
F Java Is Interpreted
Java implements several security
F Java Is Robust mechanisms to protect your system against
harm caused by stray programs.
F Java Is Secure
F Java Is Architecture-Neutral
F Java Is Portable
F Java's Performance
F Java Is Multithreaded
F Java Is Dynamic
0
Characteristics of Java
F Java Is Simple
F Java Is Object-Oriented
F Java Is Distributed
F Java Is Interpreted
F Java Is Robust
F Java Is Secure
F Java Is Architecture-Neutral Write once, run anywhere
F Java Is Portable With a Java Virtual Machine (JVM), you
can write one program that will run on any
F Java's Performance
platform.
F Java Is Multithreaded
F Java Is Dynamic
0
Characteristics of Java
F Java Is Simple
F Java Is Object-Oriented
F Java Is Distributed
F Java Is Interpreted
F Java Is Robust
F Java Is Secure
F Java Is Architecture-Neutral
Because Java is architecture neutral, Java
F Java Is Portable
programs are portable. They can be run on
F Java's Performance any platform without being recompiled.
F Java Is Multithreaded
F Java Is Dynamic
0
Characteristics of Java
F Java Is Simple
F Java Is Object-Oriented
F Java Is Distributed
F Java Is Interpreted
F Java Is Robust
F Java Is Secure
F Java Is Architecture-Neutral
Java’s performance Because Java is
F Java Is Portable
Eh architecture neutral, Java programs are
F Java's Performance portable. They can be run on any platform
without being recompiled.
F Java Is Multithreaded
F Java Is Dynamic
0
Characteristics of Java
F Java Is Simple
F Java Is Object-Oriented
F Java Is Distributed
F Java Is Interpreted
F Java Is Robust
F Java Is Secure
F Java Is Architecture-Neutral
F Java Is Portable Dm a fist
F Java's Performance Multithread programming is smoothly
integrated in Java, whereas in other languages
F Java Is Multithreaded
you have to call procedures specific to the
F Java Is Dynamic operating system to enable multithreading.
0
Characteristics of Java
F Java Is Simple
F Java Is Object-Oriented
F Java Is Distributed
F Java Is Interpreted
F Java Is Robust
F Java Is Secure
F Java Is Architecture-Neutral
F Java Is Portable
Java was designed to adapt to an evolving
F Java's Performance environment. New code can be loaded on the fly
without recompilation. There is no need for
F Java Is Multithreaded
developers to create, and for users to install, major
F Java Is Dynamic new software versions. New features can be
incorporated transparently as needed.
0
JDK Versions
F JDK 1.02 (1995)
F JDK 1.1 (1996)
F JDK 1.2 (1998)
F JDK 1.3 (2000)
F JDK 1.4 (2002)
F JDK 1.5 (2004) a. k. a. JDK 5 or Java 5
F JDK 1.6 (2006) a. k. a. JDK 6 or Java 6
F JDK 1.7 (2011) a. k. a. JDK 7 or Java 7
11.8 Q i ji
0
JDK Editions
F Java Standard Edition (J2SE)
– J2SE can be used to develop client-side standalone
applications or applets.
F Java Enterprise Edition (J2EE)
– J2EE can be used to develop server-side applications such as
Java servlets, Java ServerPages, and Java ServerFaces.
F Java Micro Edition (J2ME).
– J2ME can be used to develop applications for mobile devices
such as cell phones.
This book uses J2SE to introduce Java programming.
0
Popular Java IDEs
F NetBeans
F JCreator
F Eclipse
0
A Simple Java Program
Listing 1.1
comment
//This program prints Welcome to Java!
classname
public class iWelcome { main ad
Cpublic static void main(String[] args)D{
System.out.println("Welcome to Java!");
}a abigia
}
0
FI on m
Creating, Compiling, and
at Running Programs
away
source code d
highwdlangyen
code disk s
source
side compilertom
Bytecode
in h im
ix em
bycombiter
0
Compiling Java Source Code
You can port a source program to any machine with appropriate
compilers. The source program must be recompiled, however, because
the object program can only run on a specific machine. Nowadays
computers are networked to work together. Java was designed to run
object programs on any platform. With Java, you write the program
once, and compile the source program into a special type of object
code, known as bytecode. The bytecode can then run on any computer
with a Java Virtual Machine, as shown below. Java Virtual Machine is
a software that interprets Java bytecode.
stophere
I 0
animation
0
animation
0
animation
0
Two More Simple Examples
Output:
8
0
Two More Simple Examples
Output:
0
Anatomy of a Java Program
F Class name
F Main method
F Statements
of'am
F Statement terminator
W e TM
F Reserved words
F Comments a
F Blocks
É 0
Class Name
Every Java program must have at least one class.
Each class has a name. By convention, class names
start with an uppercase letter. In this example, the
class name is Welcome.
0
Main Method
Line 2 defines the main method. In order to run a
class, the class must contain a method named main.
The program is executed from the main method.
0
Statement
A statement represents an action or a sequence of actions.
The statement System.out.println("Welcome to Java!") in
the program in Listing 1.1 is a statement to display the
greeting "Welcome to Java!“.
0
Statement Terminator
Every statement in Java ends with a semicolon (;).
0
Reserved words
Reserved words or keywords are words that have a
specific meaning to the compiler and cannot be used for
other purposes in the program. For example, when the
compiler sees the word class, it understands that the word
after class is the name for the class.
0
Reserved words
0
Blocks
A pair of braces in a program forms a block that groups
components of a program.
0
Special Symbols
0
{ …}
0
( … )
0
;
0
// …
0
0
"…"
0
Programming Style and
Documentation
F Appropriate Comments
F Naming Conventions
F Proper Indentation and Spacing
Lines
F Block Styles
0
Appropriate Comments
Include a summary at the beginning of the program
to explain what the program does, its key features,
its supporting data structures, and any unique
techniques it uses.
0
Comments
➢They should be included to explain the purpose of the
program and describe processing steps
➢They do not affect how a program works
➢Three types of comments in Java:
Line comment: A line comment
IN is preceded by two
slashes (//) in a line.
Paragraph comment: A paragraph comment is enclosed
between /* and */ in one or multiple lines.
javadoc comment: javadoc comments begin with /**and
end with */. They are used for documenting classes, data,
and methods. They can be extracted into an HTML file
using JDK's javadoccommand.
0
Naming Conventions
F Choose meaningful and descriptive names.
F Class names:
– Capitalize the first letter of each word in the
name. For example, the class name
ComputeExpression.
0
Proper Indentation and Spacing
F Indentation
– Indent two spaces.
– Or with three to five spaces.
– Be CONSISTENT!
F Spacing
– Use blank line to separate segments of the code.
0
Block Styles
Use end-of-line style for braces.
0
Programming Errors
F An error in a program is called a bug.
F Eliminating errors is called debugging.
F Three kinds of errors:
– Syntax Errors
– Runtime Errors
– Logic Errors
0
Programming Errors
F Syntax Errors
– Errors that are detected by the compiler
– Examples: mistyping a keyword, using an
opening brace but not the closing, etc.
– Usually easy to detect, because the compiler
tells you where the error is and what caused
them.
0
Programming Errors
F Syntax Errors Example:
public class ShowSyntaxErrors {
public staticamain(String[] args) {
System.out.println("Welcome to Java);
}
}
0
Programming Errors
F Syntax Errors:
– Since a single error will often display many
lines of compile errors, it is a good practice to
fix errors from the top line and work
downward.
– Fixing errors that occur earlier in the program
may also fix additional errors that occur later.
0
Programming Errors
F Runtime Errors
– Causes the program to terminate in an
abnormal way
u Known as “crashing” or “my program crashed”
– Often caused by input mistakes, where the user
enters a value the program can not handle
– Another example: divide by zero
0
Programming Errors
F Runtime Errors Example:
0
Programming Errors
F Logic Errors
– Produces incorrect result
– Program does not run the way we intended
– Usually the result of logical mistakes
– In fact, the program “works”, but the output is
wrong due to our logical mistake.
– These errors are harder to detect.
0
Programming Errors
F Logic Errors Example:
public class ShowLogicErrors {
public static void main(String[] args) {
System.out.println("Celsius 35 is Fahrenheit degree ");
System.out.println((9 / 5) * 35 + 32);
}
} Moving É
said it
0
Programming Errors
F Most Common Errors
– Missing a closing brace, missing a semicolon,
missing quotation marks for strings, and
misspelling names are common errors for new
programmers.
0
Programming Errors
F Most Common Errors
– Missing a semicolon
0
Programming Errors
F Most Common Errors
– Missing a quotation marks
0
Programming Errors
F Most Common Errors
– Misspelling Names
0
Program Design & Problem-
Solving Techniques
0
om e e
mi mi is
What is Computer Science?
F Computer Science can be summarized with
two simple words: problem solving.
F Computer Science is the study of problems,
problem-solving, and the solutions that come
out of this problem-solving process.
F Given a problem, the goal is to develop an
algorithm to solve the problem.
F An algorithm is a step-by-step list of
instructions to solve the problem.
0
What is Programming?
F Once you have developed the algorithm on
paper, you must now “prove it” and show that
it works.
F Programming is the process of encoding your
algorithm into a programming language, so
that it can then be executed by a computer.
F But what is the first step?
F You need a solution.
F You need an algorithm!
0
So who is good at programming?
F Are you good at problem solving?
F Are you good at strategy?
F These are the core fundamentals of
programming.
0
How Do We Write a Program?
● A Computer is not intelligent.
● It cannot analyze a problem and come up with a solution.
● A human (the programmer) must analyze the problem, develop the
instructions for solving the problem, and then have the computer carry
out the instructions.
● To write a program for a computer to follow, we must go through a two-
phase process: problem solving and implementation.
7
Atlas 0
algorithm
g
184 Tawa
51
algorita
b'sail
algorithms.x
soon
text
0
1 Problem-Solving Phase
● Analysis and Specification- Understand (define) the
problem and what the solution must do.
● General Solution (Algorithm)- Specify the required
data types and the logical sequences of steps that
solve the problem. bag
0
Implementation Phase
● Concrete Solution (Program)- Translate the algorithm
(the general solution) into a programming language.
● Test- Have the computer follow the instructions.
● Then manually check the results.
● If you find errors, analyze the program and the
algorithm to determine the source of the errors,
and then make corrections.
● Once a program is tested, it enters into next phase
(maintenance).
● Maintenance requires Modification of the program to
meet changing requirements or to correct any errors
that show up while using it.
0
Steps in Program Development
1. Define the problem into three separate
components:
– inputs
– outputs
– processing steps to produce required outputs.
averageJ y 3 26
input 4 t 23
Process to t
output Essai
0
Steps in Program Development
1. Outline the solution.
– Decompose the problem to smaller steps.
– Establish a solution outline.
0
Steps in Program Development
1. Test the algorithm for correctness.
– Very important in the development of a program,
but often forgotten
– Major logic errors can be detected and corrected
at an early stage.
0
Steps in Program Development
1.
Otago Run the program on the computer.
– This step uses a program compiler and
programmer-designed test data to machine-test
the code for
u syntax errors
u logic errors
2.
are Document and maintain the program.
0
Algorithms & Flowcharts
0
● What is an algorithm?
j
● Lists the steps involved in accomplishing a task
(like a recipe)
● An algorithm must:
p
● Be lucid (clear), precise and unambiguous
● Give the correct solution in all cases
● Eventually end EI Nt go
● What is pseudocode? IN 5
● Structured English (formalized and abbreviated to
look like high-level computer language)
0
Example 1
F Write an algorithm to convert the length in feet
to centimeter.
Algorithm : Simi E
F Input the length in feet (Lft)
F Calculate the length in cm (Lcm) by
multiplying LFT with 30
F Print length in cm (LCM)
0
Example 1
Pseudocode HI w t E
0
Example 2
Write an algorithm that will read the two sides of a
rectangle and calculate its area.
Algorithm
F Input the width (W) and Length (L) of a rectangle
F Calculate the area (A) by multiplying L with W
F Print A
0
Example 2
Pseudocode
F Step 1: Input W,L
F Step 2: A L x W
F Step 3: Print A
0
Flowchart
• A graphical representation of the sequence of operations in
an information system or program.
0
Nam Symbo
Flowchart Symbols
Use in Flowchart
41801
flowchart
e l
ya
oval
Ova Denotes the beginning or end of the program
l
Mfg
Diamon
d Diamond
Denotes a decision (or
The program should continue
two
) to be
branch along
. e.g. I /THE /ELS )
madeone of
.
ifb
routes ( F N E
0
Example 2
Write an algorithm and draw a flowchart that will read the
two sides of a rectangle and calculate its area.
Pseudocode
F Step 1: Input W,L
F Step 2: A L x W
F Step 3: Print A
0
Example 3
F Write an algorithm and draw a flowchart that will
calculate the roots of a quadratic equation
0
Example 3
Algorithm :
F Input the coefficients (a, b, c) of the quadratic
equation
F Calculate d
F Calculate x1
F Calculate x2
F Print x1 and x2
0
Example 3
F Pseudocode
F Step 1: Input a, b, c
F Step 2: d sqrt ( )
F Step 3: x1 (–b + d) / (2 x a)
F Step 4: x2 (–b – d) / (2 x a)
F Step 5: Print x1, x2
0
Decision Structures
F The expression A>B is a logical expression
F it describes a condition we want to test
F if A>B is true (if A is greater than B) we take the
action on left
F print the value of A
F if A>B is false (if A is not greater than B) we take
the action on right
F print the value of B
0
Decision Structures
Y is N
A>B
Print A Print B
0
IF–THEN–ELSE STRUCTURE
F The structure in “Pseudocode” is as follows
If condition then
true alternative
else
false alternative
End if
0
IF–THEN–ELSE STRUCTURE
F The pseudocode for the flowchart is as
follows:
If A>B then
print A
else
print B
endif
0
Relational Operators
Relational Operators
Operator Description
> Greater than
< Less than
= Equal to
8 Greater than or equal to
Less than or equal to
o Not equal to
0
Example 4
F Example 1: Write an algorithm 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.
Algorithm :
F Input a set of 4 marks
F Calculate their average by summing and dividing by 4
F if average is below 60
Print “FAIL”
else
Print “PASS”
0
Example 4
F Pseudocode :
F Step 1: Input M1,M2,M3,M4
Step 2: GRADE (M1+M2+M3+M4)/4
Step 3: if (GRADE < 60) then
Print “FAIL”
else
Print “PASS”
endif
0
Example 4
GRADE (M1+M2+M3+M4)/4
Print Print
“FAIL” “PASS”
0
Example 5
F Write an algorithm that reads two values, determines the
largest value and prints the largest value with an identifying
message.
Pseudocode:
Step 1: Input VALUE1, VALUE2
Step 2: if VALUE1 > VALUE2 then
MAX VALUE1
else
MAX VALUE2
endif
Step 3: Print “The largest value is”, MAX
0
Example 5
0
Example 6
F Convert the following pseudocode to flowchart
0
Example 7
F Convert the following pseudocode to flowchart
0
Example 8
F Convert the following pseudocode to flowchart
0
Example 9
F Convert the following flowchart to pseudocode
0
Example 10
F Convert the following flowchart to pseudocode