L01 IntroductionToProgramming
L01 IntroductionToProgramming
3
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Central Processing Unit (CPU)
• Central Processing Unit (CPU, processor):
• retrieves instructions from memory and executes them
• the CPU speed is measured in cycles per second = hertz (Hz)
• 1 MegaHertz (MHz) = 1 million pulses per second
• 1 GigaHertz (GHz) = 1 billion pulses per second
Bus
4
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
(Main) Memory
• Stores data and program instructions
for CPU to execute
• ordered sequence of bytes (i.e., 8 bits
– a binary base unit)
Bus
5
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
How Data is Stored and Processed?
In binary
What’s binary? Memory address Memory content
the base-2 number system
What do humans use? . .
. .
base-10 . .
Why? 10 fingers. 2000 01001010 Encoding for character ‘J’
Why do computers like binary? 2001 01100001 Encoding for character ‘a’
2002 01110110 Encoding for character ‘v’
electronics 2003 01100001 Encoding for character ‘a’
easier to make hardware that 2004 00000011 Encoding for number 3
Binary: 0, 1
Hexadecimal: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
Octal: 0, 1, 2, 3, 4, 5, 6, 7
7
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Number Systems: Decimal
• The digits in the decimal number system are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
• A decimal number is represented using a sequence of one or more of
these digits.
• The value that each digit in the sequence represents depends on its position.
• A position in a sequence has a value that is an integral power of 10.
• e.g., the digits 7, 4, 2, and 3 in decimal number 7423 represent 7000, 400,
20, and 3, respectively: = 7 10 3 + 4 10 2 + 2 101 + 3 100
7 4 2 3
103 102 101 100 = 7000 + 400 + 20 + 3 = 7423
8
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Binary
• Computers use binary numbers internally because storage
devices like memory and disk are made to store 0s and 1s.
• Each 0 and 1 is called a bit (short for binary digit)
• Binary numbers are not intuitive to us, since we use
decimal numbers in our daily life.
• When you write a number like 20 in a program, it is
assumed to be a decimal number.
• Internally, computer software is used to convert
decimal numbers into binary numbers, and vice versa.
•A number or a text (see character encodings later)
inside a computer is stored as a sequence of 0s and 1s.
9
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Binary Numbers => Decimals
Given a binary number (bnbn − 1bn − 2...b2b1b0 )2
the equivalent decimal value is
(10)2 in binary is 1 2 + 0
1
= 2 in decimal
(10101011)2 1 27 + 0 26 + 1 25 + 0 24 + 1 23 + 0 22 + 1 2 + 1 = 171 in
in binary decimal
10
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Common Binary Powers
20 = 1
21 = 2
22 = 4
23 = 8
24 = 16
25 = 32
26 = 64
27 = 128
28 = 256
29 = 512
210 = 1024
11
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Decimal => Binary
• To convert a decimal number d to a binary number is to find the
binary digits (bn, bn − 1, bn − 2,..., b2, b1, b0 )2 such that
For example, the decimal number 123 is (1111011)2 in binary. The conversion
is conducted as follows:
0 1 3 7 15 30 61 Quotient
2 1 2 3 2 7 2 15 2 30 2 61 2 123
0 2 6 14 30 60 122
1 1 1 1 0 1 1 Remainder
b6 b5 b4 b3 b2 b1 b0
12
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Hexadecimal and Octal
• Binary numbers tend to be very long and cumbersome:
• For example: (11 1010 1011 1110)2
• Hexadecimal and octal numbers are often used to abbreviate binary
numbers:
• For example: (11_1010_1011_1110)2 = (3ABE)H
and (11_101_010_111_110)2 = (35276)8
• The hexadecimal number system has 16 digits:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F.
• The letters A, B, C, D, E, and F correspond to the decimal
numbers 10,11,12,13,14, and 15.
• Each hex digit corresponds to 4 bits (grouped from the end)
• The octal number system has 8 digits:
• 0, 1, 2, 3, 4, 5, 6, and 7
• Each octal digit corresponds to 3 bits (grouped from the end)
13
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Hexadecimals <=> Binary
Binary Decimal Hex
To convert a hexadecimal number to a
0000 0 0 binary number, simply convert each digit in
0001 1 1
0010 2 2
the hexadecimal number into a four-digit
0011 3 3 binary number. For example,
0100 4 4 (38D)H = (11_1000_1101)2
0101 5 5
0110 6 6
0111 7 7 To convert a binary number to a
1000 8 8 hexadecimal, convert every four binary
1001 9 9 digits from right to left in the binary
1010 10 A
1011 11 B
number into a hexadecimal number. For
1100 12 C example, ( 1 1 1 0 0 0 1 1 0 1 )2
1101 13 D
1110 14 E
1111 15 F (3 8 D )H
14
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Octal <=> Binary
Binary Decimal Octal
To convert an octal number to a binary
000 0 0 number, simply convert each digit in the
001 1 1 octal number into a three-digit binary
010 2 2 number. For example,
011 3 3 (1615)8 = (1_110_001_101)2
100 4 4
101 5 5
To convert a binary number to an octal
110 6 6
number, convert every three binary
111 7 7
digits from right to left in the binary
number into an octal digit. For example,
( 1 1 1 0 0 0 1 1 0 1)2
( 1 6 1 5 )8
15
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Hexadecimals => Decimals
• Given a hexadecimal number ( hnhn − 1hn − 2...h2h1h0 )H
The equivalent decimal value is
hn 16n + hn − 1 16n−1 + hn − 2 16n−2 + ... + h2 162 + h1 161 + h0 160
16
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Decimals => Hexadecimals
To convert a decimal number d to a hexadecimal number is to find
the hexadecimal digits ( hn, hn − 1, hn − 2,..., h2, h1, h0 )H such that
d = hn 16n + hn − 1 16n −1 + hn − 2 16n − 2 + ... + h2 162 + h1 161 + h0 160
These numbers can be found by
successively dividing d by 16 until the
quotient is 0. The remainders are
h0, h1, h2,..., hn − 2, hn − 1, hn 0 7 Quotient
For example, the decimal number 123 is 16 7 16 123
0
(7B)H in hexadecimal. The conversion is 112
7 11 Remainder
conducted as follows:
h1 h0
18
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
So Hardware stores 0s & 1s
How do we store text?
Numerically (i.e., using numeric codes)
Each character is stored in memory as a number
Standard character encoding sets: ASCII, Unicode
ASCII uses 1 byte per character (128 chars)
For example: ‘A’ is 65
Unicode: ~65K different characters
Multiple encodings (UTF-8, UTF-16, UTF-32,…)
o short encodings use the first bit for continuation
(variable length encodings) and may be more
19
efficient for communication (shorter encoding)
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
20
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Memory: What goes in each memory segment?
Stack Segment
variables declared inside methods (called local)
removed from memory when the method returns
Heap Segment
for dynamic data (whenever you use the operator
new)
i.e., the data for constructed objects
persistent as long as an existing a variable references
this region of memory (because garbage collection)
Global Segment
data that can be reserved at compile time
the program
global data (like static data)
constants (e.g., interned String)
21
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Programming Languages
Machine Language Assembly Language High-Level Language
22
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Programming Languages
Machine Language Assembly Language High-Level Language
…
Assembler …
ADDF3 R1, R2, R3
1101101010011010
…
…
23
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Programming Languages
Machine Language Assembly Language High-Level Language
• Example: the GCD program in x86 assembly:
24
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Programming Languages
Machine Language Assembly Language High-Level Language
27
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Source Code
How does a program run?
Compilers and interpreters.
What’s a compiler?
A software program that translates the high-level source
program into an equivalent target program (typically in machine
language), and then goes away:
28
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Interpretation
Pure Interpretation
Interpreter stays around for the execution of
the program
Interpreter is the locus of control during execution
29
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Compilation and Interpretation
Most modern language implementations
(starting with Java) include a mixture of both
compilation and interpretation
Compilation followed by interpretation:
30
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Operating Systems
The operating system (OS)
is a program that manages User
Unix
Hardware
Linux
Mac OsX
31
Android
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Why Java?
Java is somewhat different from previous languages
Java started a principle, “write once, run anywhere”
What does that mean?
Platform (and operator system) independence for
compiled Java code
How?
The Java Virtual Machine (JVM)
Java programs are compiled into Java bytecode
Bytecode is then executed by the JVM on any OS
and any platform
32
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Java, JVM, Web, and Beyond
Java Virtual Machine
A program that runs Java programs and manages
memory for Java programs.
Why?
Each platform is different (Mac, PC, Linux, Android,etc.)
The Java Development Kit (JDK) is a distribution of Java
Technology, i.e., the Java Application Programming Interface
(API), the Java compiler and the Java Virtual Machine, to
compile and execute Java programs.
33
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Java Development Kit (JDK)
JDK 1.02 (1995)
JDK 1.1 (1996), J2SE 1.2 (1998), J2SE 1.3 (2000), J2SE
1.4 (2002)
J2SE 5.0 (2004) (Major Refactoring)
Java SE 6 (2006), Java SE 7 (2011)
Java SE 8 (2014) (Major Refactoring: Language-level
support for lambda expressions)
Long Term Support (LTS)
Java SE 9 (2017)
Java SE 10, 11 (LTS) (2018)
Java SE 12, 13 (2019), Java SE 14 (March 2020)
…
Java SE 19 (2023)
34
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
JDK Editions
Java Standard Edition (J2SE)
J2SE can be used to develop client-side standalone
applications or applets.
Java Enterprise Edition (J2EE)
J2EE API and tools can be used to develop server-side
applications such as Java servlets and Java ServerPages.
Java Micro Edition (J2ME)
J2ME was used to develop applications for mobile
devices such as cell phones.
Our textbook uses J2SE to introduce Java
programming.We will use it in this class.
35
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
A Simple Java Program
// Welcome.java
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
36
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Creating, Compiling, and Running
Programs
Create/Modify Source Code
Result
37
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
If runtime errors or incorrect result
Running
Programs
in Eclipse
38
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Running Programs from command line
pfodor@sparky ~$ emacs Welcome.java
40
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Trace a Program Execution
Enter main method
41
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Trace a Program Execution
Execute statement
42
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Trace a Program Execution
43
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Anatomy of Java Programs
Comments
Reserved words
Modifiers
Statements
Blocks
Classes
Methods
The main method
44
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Comments
Three types of comments in Java:
Line comment: A line comment 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 javadoc
command.
45
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
•
Comments
The code that explains itself let it be (no need to comment).
- Good programmers can always figure out what something is done from the
code. But it is much more difficult to figure out why or how it was done.
- Just use good meaningful names for your identifiers (variables, methods).
public static int baseX2decimal(int base, String s){
int dec = 0;
for(int i=0;i<s.length();i++) {
char c = s.charAt(i);
// extract the decimal digit from the character 0..9 or A..Z for 10,11,...
int e = ('0'<=c && c<='9')
No other
? c-'0'
comments are
: ('a'<=c && c<='z')
needed.
? c-'a'+10
: c-'A'+10; Just comment
dec = dec*base + e; parts that are
} hard to
return dec; understand.
46 } (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Reserved Words (Keywords)
Reserved words or keywords are words
that have a specific meaning to the
compiler
Cannot be used for other purposes
in the program
Example: class
the word after class is the name for the class
47
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Java Keywords
abstract,assert,boolean,break,byte,
case,catch,char,class,const,continue
,default,do,double,else,enum,extends
,false,final,finally,float,for,goto,
if,implements,import,instanceof,int,
interface,long,native,new,null,
package,private,protected,public,
return,short,static,strictfp,super,
switch,synchronized,this,throw,
throws,transient,true,try,void,
volatile,while
http://docs.oracle.com/javase/tutorial
/java/nutsandbolts/_keywords.html
48
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Modifiers
Java uses certain reserved words called modifiers that
specify the properties of the data, methods, and
classes and how they can be used
Examples: public, static, private,
final, abstract, protected
A public datum, method, or class can be accessed by
other programs
A private datum or method cannot be accessed by
other programs
49
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Statements
A statement represents an action or a sequence of actions
Every statement in Java ends with a semicolon (;)
Examples:
System.out.println("Welcome to Java!");
is a statement to display the greeting "Welcome to Java!"
followed by a new line.
System.out.print("Welcome to Java!");
is a statement to display the greeting "Welcome to Java!"
without moving to the new line.
50
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Statements
Printing is overloaded for all types in Java:
System.out.println(1);
System.out.println(1.2);
System.out.println(true);
Java is weakly typed:
System.out.print("result is " + 123);
is a statement to displays "result is 123"
51
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Blocks
A pair of braces in a program forms a block
that groups components of a program.
52
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Block Styles
We use end-of-line style for braces:
End-of-line
style
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}
53
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Programming Errors
Syntax Errors
Detected by the compiler
Runtime Errors
Causes the program to abort
Logic Errors
Produces incorrect result (may or may
not run into a runtime error)
54
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Syntax Errors
public class ShowSyntaxError {
public static void main(String[] args) {
i = 30; // Detected by the compiler
System.out.println(i + 4);
}
}
55
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Runtime Error
public class ShowRuntimeError {
public static void main(String[] args) {
int i = 1 / 0;
// Runtime error: Division with 0
}
}
56
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Logic Errors
public class ShowLogicError {
// Determine if a number is between 1 and 100 inclusively
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = input.nextInt();
// Display the result
System.out.println(
"The number is between 1 and 100, inclusively: " +
((1 < number) && (number < 100)) );
// Wrong result if the entered number is 1 or 100
System.exit(0);
}
}
The program compiles and may run without a
crash, but the results are incorrect.
57
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Logic Errors Debugging
Logic errors are also called bugs
The process of finding and correcting errors is called
debugging
Methods of debugging:
hand-trace the program (i.e., catch errors by reading
the program),
insert print statements in order to show the values of
the variables
for a large, complex program, the most effective
approach for debugging is to use a debugger utility
58
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Debugger
Debugger is a program that facilitates debugging.
You can use a debugger to:
Step1: Set breakpoints where the execution
pauses when we are debugging.
Step 2: Start the debugger and Execute a single
statement at a time from the first encountered
breakpoint.
Trace into or stepping over a method.
Display variables.
59
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
60
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
61
61 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)