SlideShare a Scribd company logo
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART I: PROGRAM M IN G IN JAVA
http://introcs.cs.princeton.edu
R O B E R T S E D G E W I C K
K E V I N W A Y N E
Computer
Science
Computer
Science
An Interdisciplinary Approach
1. Basic Programming
Concepts
1.1–1.2
1. Basic Programming Concepts
•Why programming?
•Program development
•Built-in data types
•Type conversion
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART I: PROGRAM M IN G IN JAVA
CS.1.A.Basics.Why
A human being should be able to
change a diaper,
plan an invasion,
butcher a hog,
conn a ship,
design a building,
write a sonnet,
balance accounts,
build a wall,
set a bone,
comfort the dying,
take orders,
give orders,
cooperate,
act alone,
solve equations,
analyze a new problem,
pitch manure,
program a computer,
cook a tasty meal,
fight efficiently, and
die gallantly.
Specialization is for insects.
Robert A. Heinlein
Time Enough for Love (1973)
You need to know how to program
in order to be able to tell a computer what you want it to do.
Naive ideal: Natural language instructions.
Prepackaged solutions (apps) are great when what they do is what you want.
Programming enables you to make a computer do anything you want.
4
well, almost anything (stay tuned)
“Please simulate the motion of N heavenly bodies,
subject to Newton’s laws of motion and gravity.”
Ada Lovelace
Analytical
Engine
first computer
first programmer
Programming: telling a computer what to do
Programming
• Is not just for experts.
• Is a natural, satisfying and creative experience.
• Enables accomplishments not otherwise possible.
• The path to a new world of intellectual endeavor.
5
“ Instead of imagining that our main task is to instruct a
computer what to do, let us concentrate rather on explaining
to human beings what we want a computer to do. ”
− Don Knuth
Challenges
• Need to learn what computers can do.
• Need to learn a programming language. Telling a computer what to do
Telling a computer what to do
6
Kids Make Nutritious Snacks.
Red Tape Holds Up New Bridge.
Police Squad Helps Dog Bite Victim.
Local High School Dropouts Cut in Half.
Actual newspaper headlines
—Rich Pattis
Natural language
• Easy for human.
• Error-prone for computer.
Machine language
• Easy for computer.
• Error-prone for human.
High-level language
• Some difficulty for both.
• An acceptable tradeoff.
But which high-level language?
Naive ideal: A single programming language for all purposes.
for (int t = 0; t < 2000; t++)
{
a[0] = a[11] ^ a[9];
System.out.print(a[0]);
for (int i = 11; i > 0; i--)
a[i] = a[i-1];
}
Simulating an LFSR (see Prologue lecture)
10: 8A00 RA ← mem[00]
11: 8B01 RB ← mem[01]
12: 1CAB RC ← RA + RB
13: 9C02 mem[02] ← RC
14: 0000 halt
Adding two numbers (see TOY lecture)
7
Our Choice: Java
Java features
• Widely used.
• Widely available.
• Continuously under development since early 1990s.
• Embraces full set of modern abstractions.
• Variety of automatic checks for mistakes in programs. James Gosling
Java economy
• Mars rover.
• Cell phones.
• Blu-ray Disc.
• Web servers.
• Medical devices.
• Supercomputing.
• …
millions of developers
billions of devices
8
Our Choice: Java
Java features
• Widely used.
• Widely available.
• Continuously under development since early 1990s.
• Embraces full set of modern abstractions.
• Variety of automatic checks for mistakes in programs.
Facts of life
• No language is perfect.
• You need to start with some language.
Our approach
• Use a minimal subset of Java.
• Develop general programming skills that are applicable to many languages.
It’s not about the language!
“ There are only two kinds of
programming languages: those
people always [gripe] about and
those nobody uses.”
− Bjarne Stroustrup
A rich subset of the Java language vocabulary
9
built-in
types
int
long
double
char
String
boolean
flow control
if
else
for
while
boolean
operations
true
false
!
&&
||
String
operations
+
""
length()
charAt()
compareTo()
matches()
operations on
numeric types
+
-
*
/
%
++
--
punctuation
{
}
(
)
,
;
p
assignment
=
arrays
a[]
length
new
object
oriented
static
class
public
private
new
final
toString()
main()
Math
methods
Math.sin()
Math.cos()
Math.log()
Math.exp()
Math.pow()
Math.sqrt()
Math.min()
Math.max()
Math.abs()
Math.PI
System
methods
System.print()
System.println()
System.printf()
type conversion methods
Integer.parseInt()
Double.parseDouble()
Your programs will primarily consist of these plus identifiers (names) that you make up.
comparisons
<
<=
>
>=
==
!=
our Std methods
StdIn.read*()
StdOut.print*()
StdDraw.*()
StdAudio.*()
StdRandom.*()
Anatomy of your first program
10
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello, World");
}
}
text file named
HelloWorld.java
program name
main() method
body of main()
(a single statement)
Anatomy of your next several programs
11
public class MyProgram
{
public static void main(String[] args)
{
...
}
}
main() method
text file named
MyProgram.java
program name
body of main()
(a sequence of statements)
Pop quiz on "your first program"
Q. Use common sense to cope with the following error messages.
12
% javac MyProgram.java
% java MyProgram
Main method not public.
% javac MyProgram.java
MyProgram.java:3: invalid method declaration; return type required
public static main(String[] args)
^
Pop quiz on "your first program"
Q. Use common sense to cope with the following error messages.
13
% javac MyProgram.java
% java MyProgram
Main method not public.
% javac MyProgram.java
MyProgram.java:3: invalid method declaration; return type required
public static main(String[] args)
^
A. Must have forgotten “public”. public static void main(String[] args)
A. Check HelloWorld. Aha! Forgot “void”. public static void main(String[] args)
Three versions of the same program.
14
/*************************************************************************
* Compilation: javac HelloWorld.java
* Execution: java HelloWorld
*
* 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");
}
}
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } }
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello, World");
}
}
Lesson: Fonts, color, comments, and extra space are not relevant in Java
language.
6 Elements of Programming
% javac HelloWorld.java
% java HelloWorld
Hello, World
PROGRAM 1.1.1 IS AN EXAMPLE OF a complete Java program. Its name is HelloWorld,
which means that its code resides in a file named HelloWorld.java (by convention
in Java). The program’s sole action is to print a message back to the terminal win-
dow. For continuity, we will use some standard Java terms to describe the program,
but we will not define them until later in the book: PROGRAM 1.1.1 consists of a single
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
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
Program 1.1.1 Hello, World
public class HelloWorld
{
public static void main(String[] args)
{
System.out.print("Hello, World");
System.out.println();
}
}
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).
Note on program style
Different styles are appropriate in different contexts.
• Integrated development environment
• Booksite
• Book
• Your code
Enforcing consistent style can
• Stifle creativity.
• Confuse style with language.
Emphasizing consistent style can
• Make it easier to spot errors.
• Make it easier for others to read and use code.
• Enable development environment to provide visual cues.
Bottom line for you: Listen to the person assigning your grade.
15
or your boss!
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART I: PROGRAM M IN G IN JAVA
CS.1.A.Basics.Why
Image sources
http://commons.wikimedia.org/wiki/File:KnuthAtOpenContentAlliance.jpg
http://commons.wikimedia.org/wiki/File:Ada_Lovelace.jpg
http://commons.wikimedia.org/wiki/File:Babbages_Analytical_Engine,_1834-1871._(9660574685).jpg
http://commons.wikimedia.org/wiki/File:James_Gosling_2005.jpg
http://commons.wikimedia.org/wiki/File:Bjarne-stroustrup.jpg
http://blog-images.muddymatches.co.uk.s3.amazonaws.com/dating-advice/wp-content/uploads/2013/01/Bad-guy.jpg
1. Basic Programming Concepts
•Why programming?
•Program development
•Built-in data types
•Type conversion
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART I: PROGRAM M IN G IN JAVA
CS.1.B.Basics.Develop
18
Program development in Java
is a three-step process, with feedback
1. EDIT your program
• Create it by typing on your computer's keyboard.
• Result: a text file such as HelloWorld.java.
2. COMPILE it to create an executable file
• Use the Java compiler
• Result: a Java bytecode file such as HelloWorld.class
• Mistake? Go back to 1. to fix and recompile.
3. RUN your program
• Use the Java runtime.
• Result: your program’s output.
• Mistake? Go back to 1. to fix, recompile, and run.
a legal Java program that does the wrong thing
not a legal Java program
EDIT
COMPILE RUN
Software for program development
19
Any creative process involves cyclic refinement/development.
A significant difference with programs: We can use our computers to facilitate the process.
Program development environment: Software for editing, compiling and running programs.
Integrated development environment
• Often language- or system-specific.
• Can be helpful to beginners.
Bottom line: Variety of useful tools.
Virtual terminals
• Same for many languages and systems.
• Effective even for beginners.
Bottom line: Extremely simple and concise.
Two time-tested options: (Stay tuned for details).
COMPOSE
PLAY
REHEARSE
EDIT
COMPILE RUN
Program development environments: a very short history
Historical context is important in computer science.
• We regularly use old software.
• We regularly emulate old hardware.
• We depend upon old concepts and designs.
20
Widely-used methods for program development
• switches and lights
• punched cards/compiler/runtime
• editor/compiler/runtime/terminal
• editor/compiler/runtime/virtual terminal
• integrated development environment
1960
1970
1980
1990
2000
Program development with switches and lights
Circa 1970: Use switches to input binary program code and data, lights to read output.
21
Stay tuned for details [lectures on the "TOY machine"].
PDP-8, circa 1970
switches
lights
Program development with punched cards and line printers
Mid 1970s: Use punched cards to input program code and data, line printer for output.
22
IBM System 360, circa 1975
Ask your parents about the "computer center" for details.
Timesharing allowed many users to share the same computer.
Program development with timesharing terminals
Late 1970s: Use terminal for editing program, reading output, and controlling computer.
23
VT-100 terminal
VAX 11/780 circa 1977
Program development with personal computers (one approach)
1980s to present day: Use multiple virtual terminals to interact with computer.
• Edit your program using any text editor in a virtual terminal.
• Compile it by typing javac HelloWorld.java in another virtual terminal.
• Run it by typing java HelloWorld
24
virtual terminal for editor
virtual TV set
virtual terminal to compile,
run and examine output
invoke Java compiler at command line
invoke Java runtime at command line
Program development with personal computers (another approach)
25
pseudo-command line
1980s to present day: Use a customized application for program development tasks.
• 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.
“compile” button
“run” button
“Integrated Development
Environment” (IDE)
http://drjava.org
Software for program development: tradeoffs
26
Pros
• Easy-to-use language-specific tools.
• System-independent (in principle).
• Used by professionals.
• Can be helpful to beginners.
Pros
• Approach works with any language.
• Useful beyond programming.
• Used by professionals.
• Has withstood the test of time.
Cons
• Overkill for short programs?
• Big application to learn and maintain.
• Often language- or system-specific.
Cons
• Good enough for long programs?
• Dealing with independent applications.
• Working at too low a level?
This course: Used in lectures/book.
IDE
Recommended for assignments.
Virtual terminals
Lessons from short history
27
Every computer has a program development environment that allows us to
• EDIT programs.
• COMPILE them to create an executable file.
• RUN them and examine the output.
Two approaches that have served for decades and are still
effective:
• multiple virtual terminals.
Xerox Alto 1978
Apple Macintosh 1984
IBM PC 1990s
Macbook Air 2014
Wintel ultrabooks 2010s
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART I: PROGRAM M IN G IN JAVA
CS.1.B.Basics.Develop
Image sources
http://commons.wikimedia.org/wiki/Category:2013_Boston_Red_Sox_season#mediaviewer/
File:Koji_Uehara_2_on_June_15,_2013.jpg
http://thenationalforum.org/wp-content/uploads/2011/03/Legendary-Musicians.png
http://pixabay.com/p-15812/?no_redirect
1. Basic Programming Concepts
•Why programming?
•Program development
•Built-in data types
•Type conversion
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART I: PROGRAM M IN G IN JAVA
CS.1.C.Basics.Types
Built-in data types
A data type is a set of values and a set of operations on those values.
30
type set of values examples of values examples of operations
char characters
'A'
'@'
compare
String sequences of characters
"Hello World"
"CS is fun"
concatenate
int integers
17
12345
add, subtract, multiply, divide
double floating-point numbers
3.1415
6.022e23
add, subtract, multiply, divide
boolean truth values
true
false
and, or, not
Java's built-in data types
31
Pop quiz on data types
Q. What is a data type?
32
Pop quiz on data types
Q. What is a data type?
A. A set of values and a set of operations on those values.
int a;
int b;
a = 1234;
b = 99;
int c = a + b;
33
Basic Definitions
combined declaration
and assignment statement
A variable is a name that refers to a value.
A literal is a programming-language representation of a value.
A declaration statement associates a variable with a type.
An assignment statement associates a value with a variable.
variables
literals
assignment statements
declaration statements
Variables, literals, declarations, and assignments example: exchange values
34
public class Exchange
{
public static void main(String[] args)
{
int a = 1234;
int b = 99;
int t = a;
a = b;
b = t;
}
}
a b t
undeclared undeclared undeclared
int a = 1234; 1234 undeclared undeclared
int b = 99; 1234 99 undeclared
int t = a; 1234 99 1234
a = b; 99 99 1234
b = t; 99 1234 1234
This code exchanges
the values of a and b.
A trace is a table of variable values after each statement.
Q. What does this program do?
A. No way for us to confirm that it does the exchange! (Need output, stay tuned).
35
Data type for computing with strings: String
values sequences of characters
typical literals "Hello, " "1 " " * "
operation concatenate
operator +
String data type
expression value
"Hi, " + "Bob" "Hi, Bob"
"1" + " 2 " + "1" "1 2 1"
"1234" + " + " + "99" "1234 + 99"
"1234" + "99" "123499"
white
space
space
characters
Typical use: Input and output.
Examples of String operations (concatenation)
Important note:
Character interpretation depends on context!
character
"1234" + " + " + "99"
Ex 1: plus signs
operator operator
"1234" + " + " + "99"
Ex 2: spaces
white
space
Example of computing with strings: subdivisions of a ruler
36
public class Ruler
{
public static void main(String[] args)
{
String ruler1 = "1";
String ruler2 = ruler1 + " 2 " + ruler1;
String ruler3 = ruler2 + " 3 " + ruler2;
String ruler4 = ruler3 + " 4 " + ruler3;
System.out.println(ruler4);
}
}
ruler1 ruler2 ruler3 ruler4
undeclared undeclared undeclared undeclared
ruler1 = "1"; 1 undeclared undeclared undeclared
ruler2 = ruler1 + " 2 " + ruler1; 1 1 2 1 undeclared undeclared
ruler3 = ruler2 + " 3 " + ruler2; 1 1 2 1 1 2 1 3 1 2 1 undeclared
ruler4 = ruler3 + " 4 " + ruler3; 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
all + ops are concatenation
% java Ruler
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
Input and output
is necessary for us to provide data to our programs and to learn the result of computations.
37
Humans prefer to work with strings.
Programs work more efficiently with numbers.
Command-line input
• 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.
Stay tuned for many more options for input and output, and more details on type conversion.
command-line
arguments
Output
• System.out.println() method prints the given string.
• Java automatically converts numbers to strings for output.
standard output
Bird's eye view of a Java program
Input and output warmup: exchange values
38
public class Exchange
{
public static void main(String[] args)
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int t = a;
a = b;
b = t;
System.out.println(a);
System.out.println(b);
}
}
Q. What does this program do?
A. Reads two integers from the command line, then prints them out in the opposite order.
% java Exchange 5 2
2
5
% java Exchange 1234 99
99
1234
Java automatically converts int values to String for output
39
Data type for computing with integers: int
values integers between −231 and 231−1
typical literals 1234 99 0 1000000
operations add subtract multiply divide remainder
operator + − * / %
int data type
expression value comment
5 + 3 8
5 - 3 2
5 * 3 15
5 / 3 1 drop fractional part
5 % 3 2 remainder
1 / 0 runtime error
Typical usage: Math calculations; specifying programs (stay tuned).
Examples of int operations
expression value comment
3 * 5 - 2 13 * has precedence
3 + 5 / 2 5 / has precedence
3 - 5 - 2 -4 left associative
( 3 - 5 ) - 2 -4 better style
Precedence
Important note:
Only 232 different int values.
not quite the same as integers
Example of computing with integers and strings, with type conversion
40
public class IntOps
{
public static void main(String[] args)
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int sum = a + b;
int prod = a * b;
int quot = a / b;
int rem = a % b;
System.out.println(a + " + " + b + " = " + sum);
System.out.println(a + " * " + b + " = " + prod);
System.out.println(a + " / " + b + " = " + quot);
System.out.println(a + " % " + b + " = " + rem);
}
}
% java IntOps 5 2
5 + 2 = 7
5 * 2 = 10
5 / 2 = 2
5 % 2 = 1
% java IntOps 1234 99
1234 + 99 = 1333
1234 * 99 = 122166
1234 / 99 = 12
1234 % 99 = 46
Note: 1234 = 12*99 + 46
Java automatically converts int values to String for concatenation
Examples:
no double value for π.
no double value for
no double value for 1/3.
41
Data type for computing with floating point numbers: double
values real numbers
typical literals 3.14159 2.0 1.4142135623730951 6.022e23
operations add subtract multiply divide remainder
operator + − * / %
double data type
expression value
3.141 + .03 3.171
3.141 - .03 3.111
6.02e23/2 3.01e23
5.0 / 3.0 1.6666666666666667
10.0 % 3.141 0.577
Math.sqrt(2.0) 1.4142135623730951
Typical use: Scientific calculations.
Examples of double operations
expression value
1.0 / 0.0 Infinity
Math.sqrt(-1.0) NaN
Special values
Typical double values are approximations
"not a number"
. × 
√
Other built-in numeric types
42
values integers between −215 and 215−1
operations [ same as int ]
short data type
values integers between −263 and 263−1
operations [ same as int ]
long data type
values real numbers
operations [ same as double ]
float data type
Why different numeric types?
• Tradeoff between memory use and range for integers.
• Tradeoff between memory use and precision for real numbers.
short
int, float
long, double
43
Excerpts from Java’s Math Library
public class Math
double abs(double a) absolute value of a
double max(double a, double b) maximum of a and b
double min(double a, double b) minimum of a and b
double sin(double theta) sine function
double cos(double theta) cosine function
double tan(double theta) tangent function
double exp(double a) exponential (ea)
double log(double a) natural log (loge a, or ln a)
double pow(double a, double b) raise a to the bth power (ab)
long round(double a) round to the nearest integer
double random() random number in [0. 1)
double sqrt(double a) square root of a
double E value of e (constant)
double PI value of π (constant)
also defined for
int, long, and float
inverse functions also available:
asin(), acos(), and atan()
Degrees in radians. Use toDegrees() and toRadians()) to convert.
You can discard your
calculator now (please).
Example of computing with floating point numbers: quadratic equation
44
public class Quadratic
{
public static void main(String[] args)
{
// Parse coefficients from command-line.
double b = Double.parseDouble(args[0]);
double c = Double.parseDouble(args[1]);
// Calculate roots of x*x + b*x + c.
double discriminant = b*b - 4.0*c;
double d = Math.sqrt(discriminant);
double root1 = (-b + d) / 2.0;
double root2 = (-b - d) / 2.0;
// Print them out.
System.out.println(root1);
System.out.println(root2);
}
}
% java Quadratic –3.0 2.0
2.0
1.0
% java Quadratic –1.0 –1.0
1.618033988749895
-0.6180339887498949
% java Quadratic 1.0 1.0
NaN
NaN
% java Quadratic 1.0 hello
java.lang.NumberFormatException: hello
% java Quadratic 1.0
java.lang.ArrayIndexOutOfBoundsException
From algebra: the roots of are
_
+ I_ + J
I ± I J

_
_ + 
_
_ 
_
+ _ + 
Need two arguments.
(Fact of life: Not all error messages are crystal clear.)
45
Data type for computing with true and false: boolean
values true false
literals true false
operations and or not
operator  || !
boolean data type
Typical usage: Control logic and flow of a program (stay tuned).
Truth-table definitions
Proof
a !a a b a  b a || b
true false false false false false
false true false true false true
true false false true
true true true true
Q. a XOR b?
A. (!a  b) || (a  !b)
a b !a  b a  !b (!a  b) || (a  !b)
false false false false false
false true true false true
true false false true true
true true false false false
Recall first lecture
46
Comparison operators
Fundamental operations that are defined for each primitive type allow us to compare values.
• Operands: two expressions of the same type.
• Result: a value of type boolean.
operator meaning true false
== equal 2 == 2 2 == 3
!= not equal 3 != 2 2 != 2
 less than 2  13 2  2
= less than or equal 2 = 2 3 = 2
 greater than 13  2 2  13
= greater than or equal 3 = 2 2 = 3
non-negative discriminant? ( b*b - 4.0*a*c ) = 0.0
beginning of a century? ( year % 100 ) == 0
legal month? ( month = 1 )  ( month = 12 )
Examples
Typical double values are
approximations so beware
of == comparisons
Example of computing with booleans: leap year test
47
public class LeapYear
{
public static void main(String[] args)
{
int year = Integer.parseInt(args[0]);
boolean isLeapYear;
// divisible by 4 but not 100
isLeapYear = (year % 4 == 0)  (year % 100 != 0);
// or divisible by 400
isLeapYear = isLeapYear || (year % 400 == 0);
System.out.println(isLeapYear);
}
}
% java LeapYear 2016
true
% java LeapYear 1993
false
% java LeapYear 1900
false
% java LeapYear 2000
true
Q. Is a given year a leap year?
A. Yes if either (i) divisible by 400 or (ii) divisible by 4 but not 100.
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART I: PROGRAM M IN G IN JAVA
CS.1.C.Basics.Types
Image sources
http://commons.wikimedia.org/wiki/File:Calculator_casio.jpg
1. Basic Programming Concepts
•Why programming?
•Program development
•Built-in data types
•Type conversion
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART I: PROGRAM M IN G IN JAVA
CS.1.D.Basics.Conversion
50
Type checking
Types of variables involved in data-type operations always must match the definitions.
When appropriate, we often convert a value from one type to another to make types match.
The Java compiler is your friend: it checks for type errors in your code.
public class BadCode
{
public static void main(String[] args)
{
String s = 123 * 2;
}
}
% javac BadCode.java
BadCode.java:5: operator * cannot be applied to java.lang.String,int
String s = 123 * 2;
^
1 error
51
Type conversion with built-in types
Type conversion is an essential aspect of programming.
Type conversion can give counterintuitive results
but gets easier to understand with practice
Pay attention to the type of your data.
Automatic
• Convert number to string for +.
• Make numeric types match if no loss of precision.
Explicitly defined for function call.
Cast for values that belong to multiple types.
• Ex: small integers can be short, int or long.
• Ex: double values can be truncated to int values.
expression type value
x:  + 99 String x: 99
11 * 0.25 double 2.75
Integer.parseInt(123) int 123
Math.round(2.71828) long 3
(int) 2.71828 int 2
(int) Math.round(2.71828) int 3
11 * (int) 0.25 int 0
52
Pop quiz on type conversion
Q. Give the type and value of each of the following expressions.
a. ( 7 / 2 ) * 2.0
b. ( 7 / 2.0 ) * 2
c. 2 + 2
d. 2.0 + 2
53
Pop quiz on type conversion
Q. Give the type and value of each of the following expressions.
a. ( 7 / 2 ) * 2.0
b. ( 7 / 2.0 ) * 2
c. 2 + 2
d. 2.0 + 2
6.0, a double (7/2 is 3, an int)
7.0, a double
22, a String
2.02, a String
An instructive story about type conversion
Why different numeric types?
• Tradeoff between memory use and range for integers.
• Tradeoff between memory use and precision for floating-point.
54
short
int, float
long, double
What to do with an impossible conversion?
• Approach 1: Avoid doing it in the first place.
• Approach 2 (Java): Live with a well-defined result.
• Approach 3: Crash.
A conversion may be impossible.
• Example: (short) 70000.
• Short values must be between −215 and 215 − 1= 32767 .
First launch of Ariane 5, 1996
Example of type conversion put to good use: pseudo-random integers
55
public class RandomInt
{
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
double r = Math.random();
int t = (int) (r * N);
System.out.println(t);
}
}
% java RandomInt 6
3
% java RandomInt 6
0
% java RandomInt 10000
3184
System method Math.random() returns a pseudo-random double value in [0, 1).
String to int (system method)
double to int (cast) int to double (automatic)
Problem: Given N, generate a pseudo-random integer between 0 and N − 1.
Summary
A data type is a set of values and a set of operations on those values.
56
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.
• double, for computing with floating point numbers, typically for science and math apps.
• boolean, for computing with true and false, for decision making in programs.
In Java you must:
• Declare the types of your variables.
• Convert from one type to another when necessary.
• Identify and resolve type errors in order to compile your code.
Pay attention to the type of your data.
The Java compiler is your friend: it will help you identify and fix type errors in your code.
C O M P U T E R S C I E N C E
S E D G E W I C K / W A Y N E
PART I: PROGRAM M IN G IN JAVA
http://introcs.cs.princeton.edu
R O B E R T S E D G E W I C K
K E V I N W A Y N E
Computer
Science
Computer
Science
An Interdisciplinary Approach
1. Basic Programming
Concepts
1.1–1.2

More Related Content

PPTX
Introduction to programming c
PPT
Intro. to prog. c++
PPTX
Lecture1.Introduction to Computer programming.pptx
PDF
History Of C Essay
PPTX
Presentation-1.pptx
PDF
Go language presentation
PPTX
Dion computerprogramming
Introduction to programming c
Intro. to prog. c++
Lecture1.Introduction to Computer programming.pptx
History Of C Essay
Presentation-1.pptx
Go language presentation
Dion computerprogramming

Similar to computer science cousre related to python (20)

PPTX
Dion computerprogramming
PPT
Intro1
PDF
Computer Science Is The Study Of Principals And How The...
PDF
Learning to code in 2020
PPTX
Plc part 1
PDF
Solution Manual for C++ How to Program: Late Objects Version, 7/E 7th Edition...
PPTX
Mastering Python lesson3b_for_loops
DOCX
DOCX
Unit 1
PDF
Unit 4 Assignment 1 Comparative Study Of Programming...
PDF
Good programming
PPTX
Computer programming
PPTX
Modern_2.pptx for java
PDF
Scales02WhatProgrammingLanguagesShouldWeTeachOurUndergraduates
PDF
Solution Manual for C++ How to Program: Late Objects Version, 7/E 7th Edition...
PDF
4 coding from algorithms
PDF
Specification Of The Programming Language Of Java
PDF
programming language.pdf
PPT
Learn C Language
PPTX
VMC___JAVA-THIRD QUARTER-SHS TWELVE.pptx
Dion computerprogramming
Intro1
Computer Science Is The Study Of Principals And How The...
Learning to code in 2020
Plc part 1
Solution Manual for C++ How to Program: Late Objects Version, 7/E 7th Edition...
Mastering Python lesson3b_for_loops
Unit 1
Unit 4 Assignment 1 Comparative Study Of Programming...
Good programming
Computer programming
Modern_2.pptx for java
Scales02WhatProgrammingLanguagesShouldWeTeachOurUndergraduates
Solution Manual for C++ How to Program: Late Objects Version, 7/E 7th Edition...
4 coding from algorithms
Specification Of The Programming Language Of Java
programming language.pdf
Learn C Language
VMC___JAVA-THIRD QUARTER-SHS TWELVE.pptx
Ad

Recently uploaded (20)

PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
master seminar digital applications in india
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Institutional Correction lecture only . . .
PPTX
Final Presentation General Medicine 03-08-2024.pptx
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPH.pptx obstetrics and gynecology in nursing
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Microbial disease of the cardiovascular and lymphatic systems
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
master seminar digital applications in india
Module 4: Burden of Disease Tutorial Slides S2 2025
Pharmacology of Heart Failure /Pharmacotherapy of CHF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Pharma ospi slides which help in ospi learning
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Microbial diseases, their pathogenesis and prophylaxis
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Abdominal Access Techniques with Prof. Dr. R K Mishra
Institutional Correction lecture only . . .
Final Presentation General Medicine 03-08-2024.pptx
Ad

computer science cousre related to python

  • 1. C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART I: PROGRAM M IN G IN JAVA http://introcs.cs.princeton.edu R O B E R T S E D G E W I C K K E V I N W A Y N E Computer Science Computer Science An Interdisciplinary Approach 1. Basic Programming Concepts 1.1–1.2
  • 2. 1. Basic Programming Concepts •Why programming? •Program development •Built-in data types •Type conversion C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART I: PROGRAM M IN G IN JAVA CS.1.A.Basics.Why
  • 3. A human being should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, and die gallantly. Specialization is for insects. Robert A. Heinlein Time Enough for Love (1973)
  • 4. You need to know how to program in order to be able to tell a computer what you want it to do. Naive ideal: Natural language instructions. Prepackaged solutions (apps) are great when what they do is what you want. Programming enables you to make a computer do anything you want. 4 well, almost anything (stay tuned) “Please simulate the motion of N heavenly bodies, subject to Newton’s laws of motion and gravity.” Ada Lovelace Analytical Engine first computer first programmer
  • 5. Programming: telling a computer what to do Programming • Is not just for experts. • Is a natural, satisfying and creative experience. • Enables accomplishments not otherwise possible. • The path to a new world of intellectual endeavor. 5 “ Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do. ” − Don Knuth Challenges • Need to learn what computers can do. • Need to learn a programming language. Telling a computer what to do
  • 6. Telling a computer what to do 6 Kids Make Nutritious Snacks. Red Tape Holds Up New Bridge. Police Squad Helps Dog Bite Victim. Local High School Dropouts Cut in Half. Actual newspaper headlines —Rich Pattis Natural language • Easy for human. • Error-prone for computer. Machine language • Easy for computer. • Error-prone for human. High-level language • Some difficulty for both. • An acceptable tradeoff. But which high-level language? Naive ideal: A single programming language for all purposes. for (int t = 0; t < 2000; t++) { a[0] = a[11] ^ a[9]; System.out.print(a[0]); for (int i = 11; i > 0; i--) a[i] = a[i-1]; } Simulating an LFSR (see Prologue lecture) 10: 8A00 RA ← mem[00] 11: 8B01 RB ← mem[01] 12: 1CAB RC ← RA + RB 13: 9C02 mem[02] ← RC 14: 0000 halt Adding two numbers (see TOY lecture)
  • 7. 7 Our Choice: Java Java features • Widely used. • Widely available. • Continuously under development since early 1990s. • Embraces full set of modern abstractions. • Variety of automatic checks for mistakes in programs. James Gosling Java economy • Mars rover. • Cell phones. • Blu-ray Disc. • Web servers. • Medical devices. • Supercomputing. • … millions of developers billions of devices
  • 8. 8 Our Choice: Java Java features • Widely used. • Widely available. • Continuously under development since early 1990s. • Embraces full set of modern abstractions. • Variety of automatic checks for mistakes in programs. Facts of life • No language is perfect. • You need to start with some language. Our approach • Use a minimal subset of Java. • Develop general programming skills that are applicable to many languages. It’s not about the language! “ There are only two kinds of programming languages: those people always [gripe] about and those nobody uses.” − Bjarne Stroustrup
  • 9. A rich subset of the Java language vocabulary 9 built-in types int long double char String boolean flow control if else for while boolean operations true false ! && || String operations + "" length() charAt() compareTo() matches() operations on numeric types + - * / % ++ -- punctuation { } ( ) , ; p assignment = arrays a[] length new object oriented static class public private new final toString() main() Math methods Math.sin() Math.cos() Math.log() Math.exp() Math.pow() Math.sqrt() Math.min() Math.max() Math.abs() Math.PI System methods System.print() System.println() System.printf() type conversion methods Integer.parseInt() Double.parseDouble() Your programs will primarily consist of these plus identifiers (names) that you make up. comparisons < <= > >= == != our Std methods StdIn.read*() StdOut.print*() StdDraw.*() StdAudio.*() StdRandom.*()
  • 10. Anatomy of your first program 10 public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } } text file named HelloWorld.java program name main() method body of main() (a single statement)
  • 11. Anatomy of your next several programs 11 public class MyProgram { public static void main(String[] args) { ... } } main() method text file named MyProgram.java program name body of main() (a sequence of statements)
  • 12. Pop quiz on "your first program" Q. Use common sense to cope with the following error messages. 12 % javac MyProgram.java % java MyProgram Main method not public. % javac MyProgram.java MyProgram.java:3: invalid method declaration; return type required public static main(String[] args) ^
  • 13. Pop quiz on "your first program" Q. Use common sense to cope with the following error messages. 13 % javac MyProgram.java % java MyProgram Main method not public. % javac MyProgram.java MyProgram.java:3: invalid method declaration; return type required public static main(String[] args) ^ A. Must have forgotten “public”. public static void main(String[] args) A. Check HelloWorld. Aha! Forgot “void”. public static void main(String[] args)
  • 14. Three versions of the same program. 14 /************************************************************************* * Compilation: javac HelloWorld.java * Execution: java HelloWorld * * 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"); } } public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } } public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } } Lesson: Fonts, color, comments, and extra space are not relevant in Java language.
  • 15. 6 Elements of Programming % javac HelloWorld.java % java HelloWorld Hello, World PROGRAM 1.1.1 IS AN EXAMPLE OF a complete Java program. Its name is HelloWorld, which means that its code resides in a file named HelloWorld.java (by convention in Java). The program’s sole action is to print a message back to the terminal win- dow. For continuity, we will use some standard Java terms to describe the program, but we will not define them until later in the book: PROGRAM 1.1.1 consists of a single 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 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 Program 1.1.1 Hello, World public class HelloWorld { public static void main(String[] args) { System.out.print("Hello, World"); System.out.println(); } } 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). Note on program style Different styles are appropriate in different contexts. • Integrated development environment • Booksite • Book • Your code Enforcing consistent style can • Stifle creativity. • Confuse style with language. Emphasizing consistent style can • Make it easier to spot errors. • Make it easier for others to read and use code. • Enable development environment to provide visual cues. Bottom line for you: Listen to the person assigning your grade. 15 or your boss!
  • 16. C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART I: PROGRAM M IN G IN JAVA CS.1.A.Basics.Why Image sources http://commons.wikimedia.org/wiki/File:KnuthAtOpenContentAlliance.jpg http://commons.wikimedia.org/wiki/File:Ada_Lovelace.jpg http://commons.wikimedia.org/wiki/File:Babbages_Analytical_Engine,_1834-1871._(9660574685).jpg http://commons.wikimedia.org/wiki/File:James_Gosling_2005.jpg http://commons.wikimedia.org/wiki/File:Bjarne-stroustrup.jpg http://blog-images.muddymatches.co.uk.s3.amazonaws.com/dating-advice/wp-content/uploads/2013/01/Bad-guy.jpg
  • 17. 1. Basic Programming Concepts •Why programming? •Program development •Built-in data types •Type conversion C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART I: PROGRAM M IN G IN JAVA CS.1.B.Basics.Develop
  • 18. 18 Program development in Java is a three-step process, with feedback 1. EDIT your program • Create it by typing on your computer's keyboard. • Result: a text file such as HelloWorld.java. 2. COMPILE it to create an executable file • Use the Java compiler • Result: a Java bytecode file such as HelloWorld.class • Mistake? Go back to 1. to fix and recompile. 3. RUN your program • Use the Java runtime. • Result: your program’s output. • Mistake? Go back to 1. to fix, recompile, and run. a legal Java program that does the wrong thing not a legal Java program EDIT COMPILE RUN
  • 19. Software for program development 19 Any creative process involves cyclic refinement/development. A significant difference with programs: We can use our computers to facilitate the process. Program development environment: Software for editing, compiling and running programs. Integrated development environment • Often language- or system-specific. • Can be helpful to beginners. Bottom line: Variety of useful tools. Virtual terminals • Same for many languages and systems. • Effective even for beginners. Bottom line: Extremely simple and concise. Two time-tested options: (Stay tuned for details). COMPOSE PLAY REHEARSE EDIT COMPILE RUN
  • 20. Program development environments: a very short history Historical context is important in computer science. • We regularly use old software. • We regularly emulate old hardware. • We depend upon old concepts and designs. 20 Widely-used methods for program development • switches and lights • punched cards/compiler/runtime • editor/compiler/runtime/terminal • editor/compiler/runtime/virtual terminal • integrated development environment 1960 1970 1980 1990 2000
  • 21. Program development with switches and lights Circa 1970: Use switches to input binary program code and data, lights to read output. 21 Stay tuned for details [lectures on the "TOY machine"]. PDP-8, circa 1970 switches lights
  • 22. Program development with punched cards and line printers Mid 1970s: Use punched cards to input program code and data, line printer for output. 22 IBM System 360, circa 1975 Ask your parents about the "computer center" for details.
  • 23. Timesharing allowed many users to share the same computer. Program development with timesharing terminals Late 1970s: Use terminal for editing program, reading output, and controlling computer. 23 VT-100 terminal VAX 11/780 circa 1977
  • 24. Program development with personal computers (one approach) 1980s to present day: Use multiple virtual terminals to interact with computer. • Edit your program using any text editor in a virtual terminal. • Compile it by typing javac HelloWorld.java in another virtual terminal. • Run it by typing java HelloWorld 24 virtual terminal for editor virtual TV set virtual terminal to compile, run and examine output invoke Java compiler at command line invoke Java runtime at command line
  • 25. Program development with personal computers (another approach) 25 pseudo-command line 1980s to present day: Use a customized application for program development tasks. • 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. “compile” button “run” button “Integrated Development Environment” (IDE) http://drjava.org
  • 26. Software for program development: tradeoffs 26 Pros • Easy-to-use language-specific tools. • System-independent (in principle). • Used by professionals. • Can be helpful to beginners. Pros • Approach works with any language. • Useful beyond programming. • Used by professionals. • Has withstood the test of time. Cons • Overkill for short programs? • Big application to learn and maintain. • Often language- or system-specific. Cons • Good enough for long programs? • Dealing with independent applications. • Working at too low a level? This course: Used in lectures/book. IDE Recommended for assignments. Virtual terminals
  • 27. Lessons from short history 27 Every computer has a program development environment that allows us to • EDIT programs. • COMPILE them to create an executable file. • RUN them and examine the output. Two approaches that have served for decades and are still effective: • multiple virtual terminals. Xerox Alto 1978 Apple Macintosh 1984 IBM PC 1990s Macbook Air 2014 Wintel ultrabooks 2010s
  • 28. C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART I: PROGRAM M IN G IN JAVA CS.1.B.Basics.Develop Image sources http://commons.wikimedia.org/wiki/Category:2013_Boston_Red_Sox_season#mediaviewer/ File:Koji_Uehara_2_on_June_15,_2013.jpg http://thenationalforum.org/wp-content/uploads/2011/03/Legendary-Musicians.png http://pixabay.com/p-15812/?no_redirect
  • 29. 1. Basic Programming Concepts •Why programming? •Program development •Built-in data types •Type conversion C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART I: PROGRAM M IN G IN JAVA CS.1.C.Basics.Types
  • 30. Built-in data types A data type is a set of values and a set of operations on those values. 30 type set of values examples of values examples of operations char characters 'A' '@' compare String sequences of characters "Hello World" "CS is fun" concatenate int integers 17 12345 add, subtract, multiply, divide double floating-point numbers 3.1415 6.022e23 add, subtract, multiply, divide boolean truth values true false and, or, not Java's built-in data types
  • 31. 31 Pop quiz on data types Q. What is a data type?
  • 32. 32 Pop quiz on data types Q. What is a data type? A. A set of values and a set of operations on those values.
  • 33. int a; int b; a = 1234; b = 99; int c = a + b; 33 Basic Definitions combined declaration and assignment statement A variable is a name that refers to a value. A literal is a programming-language representation of a value. A declaration statement associates a variable with a type. An assignment statement associates a value with a variable. variables literals assignment statements declaration statements
  • 34. Variables, literals, declarations, and assignments example: exchange values 34 public class Exchange { public static void main(String[] args) { int a = 1234; int b = 99; int t = a; a = b; b = t; } } a b t undeclared undeclared undeclared int a = 1234; 1234 undeclared undeclared int b = 99; 1234 99 undeclared int t = a; 1234 99 1234 a = b; 99 99 1234 b = t; 99 1234 1234 This code exchanges the values of a and b. A trace is a table of variable values after each statement. Q. What does this program do? A. No way for us to confirm that it does the exchange! (Need output, stay tuned).
  • 35. 35 Data type for computing with strings: String values sequences of characters typical literals "Hello, " "1 " " * " operation concatenate operator + String data type expression value "Hi, " + "Bob" "Hi, Bob" "1" + " 2 " + "1" "1 2 1" "1234" + " + " + "99" "1234 + 99" "1234" + "99" "123499" white space space characters Typical use: Input and output. Examples of String operations (concatenation) Important note: Character interpretation depends on context! character "1234" + " + " + "99" Ex 1: plus signs operator operator "1234" + " + " + "99" Ex 2: spaces white space
  • 36. Example of computing with strings: subdivisions of a ruler 36 public class Ruler { public static void main(String[] args) { String ruler1 = "1"; String ruler2 = ruler1 + " 2 " + ruler1; String ruler3 = ruler2 + " 3 " + ruler2; String ruler4 = ruler3 + " 4 " + ruler3; System.out.println(ruler4); } } ruler1 ruler2 ruler3 ruler4 undeclared undeclared undeclared undeclared ruler1 = "1"; 1 undeclared undeclared undeclared ruler2 = ruler1 + " 2 " + ruler1; 1 1 2 1 undeclared undeclared ruler3 = ruler2 + " 3 " + ruler2; 1 1 2 1 1 2 1 3 1 2 1 undeclared ruler4 = ruler3 + " 4 " + ruler3; 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 all + ops are concatenation % java Ruler 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
  • 37. Input and output is necessary for us to provide data to our programs and to learn the result of computations. 37 Humans prefer to work with strings. Programs work more efficiently with numbers. Command-line input • 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. Stay tuned for many more options for input and output, and more details on type conversion. command-line arguments Output • System.out.println() method prints the given string. • Java automatically converts numbers to strings for output. standard output Bird's eye view of a Java program
  • 38. Input and output warmup: exchange values 38 public class Exchange { public static void main(String[] args) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int t = a; a = b; b = t; System.out.println(a); System.out.println(b); } } Q. What does this program do? A. Reads two integers from the command line, then prints them out in the opposite order. % java Exchange 5 2 2 5 % java Exchange 1234 99 99 1234 Java automatically converts int values to String for output
  • 39. 39 Data type for computing with integers: int values integers between −231 and 231−1 typical literals 1234 99 0 1000000 operations add subtract multiply divide remainder operator + − * / % int data type expression value comment 5 + 3 8 5 - 3 2 5 * 3 15 5 / 3 1 drop fractional part 5 % 3 2 remainder 1 / 0 runtime error Typical usage: Math calculations; specifying programs (stay tuned). Examples of int operations expression value comment 3 * 5 - 2 13 * has precedence 3 + 5 / 2 5 / has precedence 3 - 5 - 2 -4 left associative ( 3 - 5 ) - 2 -4 better style Precedence Important note: Only 232 different int values. not quite the same as integers
  • 40. Example of computing with integers and strings, with type conversion 40 public class IntOps { public static void main(String[] args) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int sum = a + b; int prod = a * b; int quot = a / b; int rem = a % b; System.out.println(a + " + " + b + " = " + sum); System.out.println(a + " * " + b + " = " + prod); System.out.println(a + " / " + b + " = " + quot); System.out.println(a + " % " + b + " = " + rem); } } % java IntOps 5 2 5 + 2 = 7 5 * 2 = 10 5 / 2 = 2 5 % 2 = 1 % java IntOps 1234 99 1234 + 99 = 1333 1234 * 99 = 122166 1234 / 99 = 12 1234 % 99 = 46 Note: 1234 = 12*99 + 46 Java automatically converts int values to String for concatenation
  • 41. Examples: no double value for π. no double value for no double value for 1/3. 41 Data type for computing with floating point numbers: double values real numbers typical literals 3.14159 2.0 1.4142135623730951 6.022e23 operations add subtract multiply divide remainder operator + − * / % double data type expression value 3.141 + .03 3.171 3.141 - .03 3.111 6.02e23/2 3.01e23 5.0 / 3.0 1.6666666666666667 10.0 % 3.141 0.577 Math.sqrt(2.0) 1.4142135623730951 Typical use: Scientific calculations. Examples of double operations expression value 1.0 / 0.0 Infinity Math.sqrt(-1.0) NaN Special values Typical double values are approximations "not a number" . × √
  • 42. Other built-in numeric types 42 values integers between −215 and 215−1 operations [ same as int ] short data type values integers between −263 and 263−1 operations [ same as int ] long data type values real numbers operations [ same as double ] float data type Why different numeric types? • Tradeoff between memory use and range for integers. • Tradeoff between memory use and precision for real numbers. short int, float long, double
  • 43. 43 Excerpts from Java’s Math Library public class Math double abs(double a) absolute value of a double max(double a, double b) maximum of a and b double min(double a, double b) minimum of a and b double sin(double theta) sine function double cos(double theta) cosine function double tan(double theta) tangent function double exp(double a) exponential (ea) double log(double a) natural log (loge a, or ln a) double pow(double a, double b) raise a to the bth power (ab) long round(double a) round to the nearest integer double random() random number in [0. 1) double sqrt(double a) square root of a double E value of e (constant) double PI value of π (constant) also defined for int, long, and float inverse functions also available: asin(), acos(), and atan() Degrees in radians. Use toDegrees() and toRadians()) to convert. You can discard your calculator now (please).
  • 44. Example of computing with floating point numbers: quadratic equation 44 public class Quadratic { public static void main(String[] args) { // Parse coefficients from command-line. double b = Double.parseDouble(args[0]); double c = Double.parseDouble(args[1]); // Calculate roots of x*x + b*x + c. double discriminant = b*b - 4.0*c; double d = Math.sqrt(discriminant); double root1 = (-b + d) / 2.0; double root2 = (-b - d) / 2.0; // Print them out. System.out.println(root1); System.out.println(root2); } } % java Quadratic –3.0 2.0 2.0 1.0 % java Quadratic –1.0 –1.0 1.618033988749895 -0.6180339887498949 % java Quadratic 1.0 1.0 NaN NaN % java Quadratic 1.0 hello java.lang.NumberFormatException: hello % java Quadratic 1.0 java.lang.ArrayIndexOutOfBoundsException From algebra: the roots of are _ + I_ + J I ± I J _ _ + _ _ _ + _ + Need two arguments. (Fact of life: Not all error messages are crystal clear.)
  • 45. 45 Data type for computing with true and false: boolean values true false literals true false operations and or not operator || ! boolean data type Typical usage: Control logic and flow of a program (stay tuned). Truth-table definitions Proof a !a a b a b a || b true false false false false false false true false true false true true false false true true true true true Q. a XOR b? A. (!a b) || (a !b) a b !a b a !b (!a b) || (a !b) false false false false false false true true false true true false false true true true true false false false Recall first lecture
  • 46. 46 Comparison operators Fundamental operations that are defined for each primitive type allow us to compare values. • Operands: two expressions of the same type. • Result: a value of type boolean. operator meaning true false == equal 2 == 2 2 == 3 != not equal 3 != 2 2 != 2 less than 2 13 2 2 = less than or equal 2 = 2 3 = 2 greater than 13 2 2 13 = greater than or equal 3 = 2 2 = 3 non-negative discriminant? ( b*b - 4.0*a*c ) = 0.0 beginning of a century? ( year % 100 ) == 0 legal month? ( month = 1 ) ( month = 12 ) Examples Typical double values are approximations so beware of == comparisons
  • 47. Example of computing with booleans: leap year test 47 public class LeapYear { public static void main(String[] args) { int year = Integer.parseInt(args[0]); boolean isLeapYear; // divisible by 4 but not 100 isLeapYear = (year % 4 == 0) (year % 100 != 0); // or divisible by 400 isLeapYear = isLeapYear || (year % 400 == 0); System.out.println(isLeapYear); } } % java LeapYear 2016 true % java LeapYear 1993 false % java LeapYear 1900 false % java LeapYear 2000 true Q. Is a given year a leap year? A. Yes if either (i) divisible by 400 or (ii) divisible by 4 but not 100.
  • 48. C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART I: PROGRAM M IN G IN JAVA CS.1.C.Basics.Types Image sources http://commons.wikimedia.org/wiki/File:Calculator_casio.jpg
  • 49. 1. Basic Programming Concepts •Why programming? •Program development •Built-in data types •Type conversion C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART I: PROGRAM M IN G IN JAVA CS.1.D.Basics.Conversion
  • 50. 50 Type checking Types of variables involved in data-type operations always must match the definitions. When appropriate, we often convert a value from one type to another to make types match. The Java compiler is your friend: it checks for type errors in your code. public class BadCode { public static void main(String[] args) { String s = 123 * 2; } } % javac BadCode.java BadCode.java:5: operator * cannot be applied to java.lang.String,int String s = 123 * 2; ^ 1 error
  • 51. 51 Type conversion with built-in types Type conversion is an essential aspect of programming. Type conversion can give counterintuitive results but gets easier to understand with practice Pay attention to the type of your data. Automatic • Convert number to string for +. • Make numeric types match if no loss of precision. Explicitly defined for function call. Cast for values that belong to multiple types. • Ex: small integers can be short, int or long. • Ex: double values can be truncated to int values. expression type value x: + 99 String x: 99 11 * 0.25 double 2.75 Integer.parseInt(123) int 123 Math.round(2.71828) long 3 (int) 2.71828 int 2 (int) Math.round(2.71828) int 3 11 * (int) 0.25 int 0
  • 52. 52 Pop quiz on type conversion Q. Give the type and value of each of the following expressions. a. ( 7 / 2 ) * 2.0 b. ( 7 / 2.0 ) * 2 c. 2 + 2 d. 2.0 + 2
  • 53. 53 Pop quiz on type conversion Q. Give the type and value of each of the following expressions. a. ( 7 / 2 ) * 2.0 b. ( 7 / 2.0 ) * 2 c. 2 + 2 d. 2.0 + 2 6.0, a double (7/2 is 3, an int) 7.0, a double 22, a String 2.02, a String
  • 54. An instructive story about type conversion Why different numeric types? • Tradeoff between memory use and range for integers. • Tradeoff between memory use and precision for floating-point. 54 short int, float long, double What to do with an impossible conversion? • Approach 1: Avoid doing it in the first place. • Approach 2 (Java): Live with a well-defined result. • Approach 3: Crash. A conversion may be impossible. • Example: (short) 70000. • Short values must be between −215 and 215 − 1= 32767 . First launch of Ariane 5, 1996
  • 55. Example of type conversion put to good use: pseudo-random integers 55 public class RandomInt { public static void main(String[] args) { int N = Integer.parseInt(args[0]); double r = Math.random(); int t = (int) (r * N); System.out.println(t); } } % java RandomInt 6 3 % java RandomInt 6 0 % java RandomInt 10000 3184 System method Math.random() returns a pseudo-random double value in [0, 1). String to int (system method) double to int (cast) int to double (automatic) Problem: Given N, generate a pseudo-random integer between 0 and N − 1.
  • 56. Summary A data type is a set of values and a set of operations on those values. 56 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. • double, for computing with floating point numbers, typically for science and math apps. • boolean, for computing with true and false, for decision making in programs. In Java you must: • Declare the types of your variables. • Convert from one type to another when necessary. • Identify and resolve type errors in order to compile your code. Pay attention to the type of your data. The Java compiler is your friend: it will help you identify and fix type errors in your code.
  • 57. C O M P U T E R S C I E N C E S E D G E W I C K / W A Y N E PART I: PROGRAM M IN G IN JAVA http://introcs.cs.princeton.edu R O B E R T S E D G E W I C K K E V I N W A Y N E Computer Science Computer Science An Interdisciplinary Approach 1. Basic Programming Concepts 1.1–1.2