Basic Programming Concepts: Omputer Cience
Basic Programming Concepts: Omputer Cience
S E D G E W I C K / W A Y N E S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA PA R T I : P R O G R A M M I N G I N J AVA
Computer Concepts
• Program development
http://introcs.cs.princeton.edu
CS.1.A.Basics.Why
− Don Knuth
Naive ideal: A single programming language for all purposes.
5 6
} <= Math.PI
StdIn.read*() Math.abs() }
false a[]
StdOut.print*() Math.PI
( > ! length type conversion methods
StdDraw.*()
) >= && new Integer.parseInt() StdAudio.*()
, == || body of main()
Double.parseDouble() StdRandom.*() (a single statement)
; !=
Your programs will primarily consist of these plus identifiers (names) that you make up.
9 10
Anatomy of your next several programs Pop quiz on "your first program"
% javac MyProgram.java
MyProgram.java:3: invalid method declaration; return type required
}
public static main(String[] args)
} ^
body of main()
(a sequence of statements)
11 12
Pop quiz on "your first program" Three versions of the same program.
Q. Use common sense to cope with the following error messages. public class HelloWorld
{
public static void main(String[] args)
{
% javac MyProgram.java System.out.println("Hello, World");
}
% java MyProgram }
Main method not public.
/*************************************************************************
* Compilation: javac HelloWorld.java
* Execution: java HelloWorld
*
A. Must have forgotten “public”. public static void main(String[] args) * Prints "Hello, World". By tradition, this is everyone's first program.
*
* % java HelloWorld
* Hello, World
*
*************************************************************************/
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } }
A. Check HelloWorld. Aha! Forgot “void”. public static void main(String[] args)
Lesson: Fonts, color, comments, and extra space are not relevant in Java
13 language. 14
}
}
http://blog-images.muddymatches.co.uk.s3.amazonaws.com/dating-advice/wp-content/uploads/2013/01/Bad-guy.jpg
• Confuse style with language. This code is a Java program that accomplishes a simple task. It is traditionally a beginner’s first
program. The box below shows what happens when you compile and execute the program. The
terminal application gives a command prompt (% in this book) and executes the commands
that you type (javac and then java in the example below). The result in this case is that the
program prints a message in the terminal window (the third line).
% javac HelloWorld.java
• Make it easier for others to read and use code. class named HelloWorld that has a single method named main(). This method uses
two other methods named System.out.print() and System.out.println() to
do the job. (When referring to a method in the text, we use () after the name to
distinguish it from other kinds of names.) Until SECTION 2.1, where we learn about
• Enable development environment to provide visual cues. classes that define multiple methods, all of our classes will have this same structure.
For the time being, you can think of “class” as meaning “program.”
The first line of a method specifies its name and other information; the rest is
a sequence of statements enclosed in braces and each followed by a semicolon. For
the time being, you can think of “programming” as meaning “specifying a class
Bottom line for you: Listen to the person assigning your grade.
15 CS.1.A.Basics.Why
or your boss!
COMPUTER SCIENCE Program development in Java
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
is a three-step process, with feedback
CS.1.B.Basics.Develop 18
Software for program development Program development environments: a very short history
Any creative process involves cyclic refinement/development. Historical context is important in computer science.
• We regularly use old software.
EDIT
COMPOSE
• We regularly emulate old hardware.
• We depend upon old concepts and designs.
COMPILE RUN
REHEARSE PLAY
• punched cards/compiler/runtime
Program development environment: Software for editing, compiling and running programs. 1970
• editor/compiler/runtime/terminal
• editor/compiler/runtime/virtual terminal 1980
Two time-tested options: (Stay tuned for details).
• integrated development environment
1990
Circa 1970: Use switches to input binary program code and data, lights to read output. Mid 1970s: Use punched cards to input program code and data, line printer for output.
switches
Stay tuned for details [lectures on the "TOY machine"]. Ask your parents about the "computer center" for details.
21 22
Program development with timesharing terminals Program development with personal computers (one approach)
Late 1970s: Use terminal for editing program, reading output, and controlling computer. 1980s to present day: Use multiple virtual terminals to interact with computer.
• Edit your program using any text editor in a virtual terminal.
VAX 11/780 circa 1977
• Compile it by typing javac HelloWorld.java in another virtual terminal.
VT-100 terminal
• Run it by typing java HelloWorld
virtual TV set
1980s to present day: Use a customized application for program development tasks.
Virtual terminals IDE
• Edit your program using the built-in text editor.
• Compile it by clicking the “compile” button.
• Run it by clicking the “run” button or using the pseudo-command line. Pros Pros
• Approach works with any language. • Easy-to-use language-specific tools.
• Useful beyond programming. • System-independent (in principle).
“Integrated Development
Environment” (IDE) • Used by professionals. • Used by professionals.
“run” button
• Has withstood the test of time. • Can be helpful to beginners.
http://drjava.org
“compile” button
Cons Cons
• Good enough for long programs? • Overkill for short programs?
• Dealing with independent applications. • Big application to learn and maintain.
pseudo-command line
• Working at too low a level? • Often language- or system-specific.
'A'
char characters compare
'@'
1. Basic Programming Concepts "Hello World"
String sequences of characters concatenate
"CS is fun"
• Why programming? 17
int integers add, subtract, multiply, divide
• Program development 12345
31 32
Basic Definitions Variables, literals, declarations, and assignments example: exchange values
A. No way for us to confirm that it does the exchange! (Need output, stay tuned).
33 34
Data type for computing with strings: String Example of computing with strings: subdivisions of a ruler
Typical use: Input and output. ruler4 = ruler3 + " 4 " + ruler3; 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
35 36
Input and output Input and output warmup: exchange values
is necessary for us to provide data to our programs and to learn the result of computations.
command-line
public class Exchange
Humans prefer to work with strings. arguments {
Programs work more efficiently with numbers. public static void main(String[] args)
{ % java Exchange 5 2
int a = Integer.parseInt(args[0]); 2
int b = Integer.parseInt(args[1]); 5
Output int t = a;
standard output
• System.out.println() method prints the given string. a = b; % java Exchange 1234 99
b = t; 99
• Java automatically converts numbers to strings for output. Bird's eye view of a Java program
1234
System.out.println(a);
System.out.println(b);
}
Command-line input } Java automatically converts int values to String for output
• Strings you type after the program name are available as args[0], args[1], ... at run time.
• Q. How do we give an integer as command-line input?
• A. Need to call system method Integer.parseInt() to convert the strings to integers. Q. What does this program do?
Stay tuned for many more options for input and output, and more details on type conversion. A. Reads two integers from the command line, then prints them out in the opposite order.
37 38
Data type for computing with integers: int Example of computing with integers and strings, with type conversion
values real numbers values integers between 215 and 215 1 values integers between 263 and 263 1
. ×
typical literals 3.14159 2.0 1.4142135623730951 6.022e23
Typical double values are approximations
operations [ same as int ] operations [ same as int ]
operations add subtract multiply divide remainder
Examples:
operator + * / %
no double value for π. float data type
√
no double value for
values real numbers
Examples of double operations no double value for 1/3.
expression value operations [ same as double ]
Math.sqrt(2.0) 1.4142135623730951
"not a number"
short
int, float
Typical use: Scientific calculations. long, double
41 42
Excerpts from Java’s Math Library Example of computing with floating point numbers: quadratic equation
double exp(double a) exponential (ea) // Calculate roots of x*x + b*x + c. % java Quadratic 1.0 1.0
double log(double a) natural log (loge a, or ln a) double discriminant = b*b - 4.0*c; NaN + +
double d = Math.sqrt(discriminant); NaN
double pow(double a, double b) raise a to the bth power (ab) double root1 = (-b + d) / 2.0;
double root2 = (-b - d) / 2.0; % java Quadratic 1.0 hello
long round(double a) round to the nearest integer java.lang.NumberFormatException: hello
// Print them out.
double random() random number in [0. 1) System.out.println(root1); % java Quadratic 1.0
double sqrt(double a) square root of a System.out.println(root2); java.lang.ArrayIndexOutOfBoundsException
}
}
double E value of e (constant) Need two arguments.
You can discard your (Fact of life: Not all error messages are crystal clear.)
double PI value of π (constant) calculator now (please).
43 44
Data type for computing with true and false: boolean Comparison operators
boolean data type Truth-table definitions Fundamental operations that are defined for each primitive type allow us to compare values.
values true false a !a a b a && b a || b
• Operands: two expressions of the same type.
• Result: a value of type boolean.
literals true false true false false false false false
false true false true false true
operations and or not
true false false true operator meaning true false
operator && || ! true true true true == equal 2 == 2 2 == 3
!= not equal 3 != 2 2 != 2
Recall first lecture < less than 2 < 13 2 < 2
Proof a b !a && b a && !b (!a && b) || (a && !b) <= less than or equal 2 <= 2 3 <= 2
Q. a XOR b?
false false false false false > greater than 13 > 2 2 < 13
A. (!a && b) || (a && !b)
false true true false true >= greater than or equal 3 >= 2 2 >= 3
true false false true true
Typical double values are
true true false false false Examples non-negative discriminant? ( b*b - 4.0*a*c ) >= 0.0 approximations so beware
of == comparisons
beginning of a century? ( year % 100 ) == 0
Typical usage: Control logic and flow of a program (stay tuned). legal month? ( month >= 1 ) && ( month <= 12 )
45 46
http://commons.wikimedia.org/wiki/File:Calculator_casio.jpg
47 CS.1.C.Basics.Types
COMPUTER SCIENCE Type checking
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
Types of variables involved in data-type operations always must match the definitions.
The Java compiler is your friend: it checks for type errors in your code.
• Why programming? }
}
• Program development
• Built-in data types % javac BadCode.java
BadCode.java:5: operator * cannot be applied to java.lang.String,int
• Type conversion String s = "123" * 2;
^
1 error
When appropriate, we often convert a value from one type to another to make types match.
CS.1.D.Basics.Conversion 50
Cast for values that belong to multiple types. (int) 2.71828 int 2 c. "2" + 2
• Ex: small integers can be short, int or long. (int) Math.round(2.71828) int 3
• Ex: double values can be truncated to int values. 11 * (int) 0.25 int 0
d. 2.0 + "2"
Type conversion can give counterintuitive results
Pay attention to the type of your data.
but gets easier to understand with practice
51 52
Pop quiz on type conversion An instructive story about type conversion
Q. Give the type and value of each of the following expressions. Why different numeric types?
• Tradeoff between memory use and range for integers.
• Tradeoff between memory use and precision for floating-point.
System method Math.random() returns a pseudo-random double value in [0, 1). A data type is a set of values and a set of operations on those values.
Problem: Given N, generate a pseudo-random integer between 0 and N 1. Commonly-used built-in data types in Java
• String, for computing with sequence of characters, for input and output.
• int, for computing with integers, for math calculations in programs.
public class RandomInt
{ • double, for computing with floating point numbers, typically for science and math apps.
public static void main(String[] args) • boolean, for computing with true and false, for decision making in programs.
{
int N = Integer.parseInt(args[0]); String to int (system method)
double r = Math.random();
In Java you must:
int t = (int) (r * N);
• Declare the types of your variables.
double to int (cast) int to double (automatic)
% java RandomInt 6
System.out.println(t); • Convert from one type to another when necessary.
3
}
• Identify and resolve type errors in order to compile your code.
} % java RandomInt 6
0 Pay attention to the type of your data.
1. Basic Programming
Computer Concepts
Science An Interdisciplinary Approach
ROBERT SEDGEWICK
1.1–1.2 K E V I N WAY N E
http://introcs.cs.princeton.edu