0% found this document useful (0 votes)
15 views50 pages

Basic Programming Concepts in Java

The document introduces basic programming concepts, emphasizing the importance of programming for instructing computers and the creative process involved. It covers the development process in Java, including editing, compiling, and running programs, as well as built-in data types and their operations. The document also highlights the choice of Java as a programming language due to its widespread use and modern features.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views50 pages

Basic Programming Concepts in Java

The document introduces basic programming concepts, emphasizing the importance of programming for instructing computers and the creative process involved. It covers the development process in Java, including editing, compiling, and running programs, as well as built-in data types and their operations. The document also highlights the choice of Java as a programming language due to its widespread use and modern features.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

COMPUTER SCIENCE

S E D G E W I C K / W A Y N E

2. Basic Programming
Concepts
Sections 1.1 and 1.2

[Link]
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E

2. Basic Programming Concepts


• Why programming?
• Program development
• Built-in data types
• Type conversion

[Link]
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.

“Please simulate the motion of N heavenly bodies,


subject to Newton’s laws of motion and gravity.”

Prepackaged solutions (apps) are great when what they do is what you want.

Programming enables you to make a computer do anything you want. well, almost anything (stay tuned)

first programmer first computer

Analytical
Ada Lovelace
Engine
3
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.

Challenges
• Need to learn what computers can do.
• Need to learn a programming language. Telling a computer what to do

“ 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
4
Telling a computer what to do

Machine language Natural language High-level language


• Easy for computer. • Easy for human. • Some difficulty for both.
• Error-prone for human. • Error-prone for computer. • An acceptable tradeoff.

K ids Make for (int t = 0; t < 2000; t++)


Nutritious
10: 8A00 RA ← mem[00] Snacks. {
RB ← mem[01] ge.
11: 8B01 p New Brid a[0] = (a[11] ^ a[9]);
12: 1CAB RC ← RA + RB Red Ta pe Holds U [Link](a[0]);
13: 9C02 mem[02] ← RC Police Squad Helps Dog Bite Victim. for (int i = 11; i > 0; i--)
14: 0000 halt a[i] = a[i-1];
opouts Cut in Half. }
Adding two numbers (see Lecture 10) Local High School Dr
Actual newspaper headlines Simulating an LFSR (see Lecture 1)
—Rich Pattis

But which high-level language?

Naive ideal: A single programming language for all purposes.


5
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

$100 billion,
Java economy 5 million developers

• Mars rover.
• Cell phones.
• Blu-ray Disc.
• Web servers.
• Medical devices.
• Supercomputing.
•…
6
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 “ There are only two kinds of


• No language is perfect. programming languages: those
• You need to start with some language. people always [gripe] about and
those nobody uses.”
− Bjarne Stroustrup
Our approach
• Use a minimal subset of Java.
• Develop general programming skills that are applicable to many languages.

It’s not about the language!


7
A rich subset of the Java language vocabulary

built-in operations on String object Math


types numeric types operations assignment oriented methods
int + + = static [Link]() p

long - "" class [Link]()


double * length() flow control public [Link]()
System
char / charAt() if private [Link]() methods
String % compareTo() else new [Link]() [Link]()
boolean ++ matches() for final [Link]() [Link]()
-- while toString() [Link]() [Link]()
boolean main() [Link]()
punctuation comparisons operations
our Std methods
{ < true arrays [Link]()
[Link]*()
} <= false [Link]
a[]
[Link]*()
( > ! length type conversion methods
StdDraw.*()
) >= && new [Link]() StdAudio.*()
, == ||
[Link]() StdRandom.*()
; !=

Your programs will primarily consist of these plus identifiers (names) that you make up.
8
Anatomy of your first program

program name

main() method
text file named
[Link] public class HelloWorld
{
public static void main(String[] args)
{
[Link]("Hello, World");
}
}

body of main()
(a single statement)

9
Anatomy of your next several programs

program name

main() method
text file named
[Link] public class MyProgram
{
public static void main(String[] args)
{
...

}
}

body of main()
(a sequence of statements)

10
Pop quiz on "your first program" (easy if you did Exercise 1.1.2)

Q. Use common sense to cope with the following error messages.

% javac [Link]
% java MyProgram
Main method not public.

% javac [Link]
[Link]: invalid method declaration; return type required
public static main(String[] args)
^

11
Three versions of the same program.

public class HelloWorld


{
public static void main(String[] args)
{
[Link]("Hello, World");
}
}

/*************************************************************************
* Compilation: javac [Link]
* 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) {


[Link]("Hello, World");
}
}

public class HelloWorld { public static void main(String[] args) { [Link]("Hello, World"); } }

Lesson: Fonts, color, comments, and extra space are not relevant to Java.
12
Note on program style
Different styles are appropriate in different contexts.
• DrJava
• 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 this course: Life is easiest if you use DrJava style.
13
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E

2. Basic Programming Concepts


• Why programming?
• Program development
• Built-in data types
• Type conversion

[Link]
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 [Link].

EDIT
2. COMPILE it to create an executable file
• Use the Java compiler
• Result: a Java bytecode file file such as [Link]
• Mistake? Go back to 1. to fix and recompile. COMPILE RUN
not a legal Java program

3. RUN your program


• Use the Java runtime.
• Result: your program’s output.
• Mistake? Go back to 1. to fix, recompile, and execute
a legal Java program that does the wrong thing

15
Software for program development

Any creative process involves cyclic refinement/development.

EDIT
COMPOSE

COMPILE RUN
REHEARSE PLAY

A significant difference with programs: We can use our computers to faciliate the process.

Program development environment: Software for editing, compiling and running programs.

Two time-tested options: (Stay tuned for details).

Virtual terminals Integrated development environment


• Same for many languages and systems. • Often language- or system-specific.
• Effective even for beginners. • Can be helpful to beginners.
Bottom line: Extremely simple and concise. Bottom line: Variety of useful tools.
16
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.

Widely-used methods for program development


• switches and lights 1960

• punched cards/compiler/runtime
1970
• editor/compiler/runtime/terminal
• editor/compiler/runtime/virtual terminal 1980

• integrated development environment


1990

2000

17
Program development with switches and lights

Circa 1970: Use switches to input binary program code and data, lights to read output.

PDP-8, circa 1970 lights

switches

Stay tuned for details [lectures on the "TOY machine"].


18
Program development with punched cards and line printers

Mid 1970s: Use punched cards to input program code and data, line printer for output.

IBM System 360, circa 1975

Ask your parents about the "computer center" for details.


19
Program development with timesharing terminals

Late 1970s: Use terminal for editing program, reading output, and controlling computer.

VAX 11/780 circa 1977

VT-100 terminal

Timesharing allowed many users to share the same computer.


20
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 [Link] in another virtual terminal.
• Run it by typing javac [Link]

virtual terminal for editor virtual terminal to compile,


run and examine output

invoke Java compiler at command line

invoke Java runtime at command line

virtual TV set

21
Program development with personal computers (another approach)

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.

“Integrated Development
Environment” (IDE)

[Link]
“compile” button

“run” button

pseudo-command line

22
Software for program development: tradeoffs

Virtual terminals DrJava IDE

Pros Pros
• Approach works with any language. • Easy-to-use language-specific tools.
• Useful beyond programming. • System-independent (in principle).
• Used by professionals. • Used by professionals.
• Has withstood the test of time. • Can be helpful to beginners.

Cons Cons
• Good enough for long programs? • Overkill for short programs?
• Dealing with independent applications. • Big application to learn and maintain.
• Working at too low a level? • Often language- or system-specific.

This course: Used in lectures/book. Recommended for assignments.


23
Lessons from short history

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.
• integrated development environments.

Macbook Air 2014

Apple Macintosh 1984


IBM PC 1990s
Wintel ultrabooks 2010s
Xerox Alto 1978
24
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E

2. Basic Programming Concepts


• Why programming?
• Program development
• Built-in data types
• Type conversion

[Link]
Built-in data types

A data type is a set of values and a set of operations on those values.

type set of values examples of values examples of operations

'A'
char characters compare
'@'

"Hello World"
String sequences of characters concatenate
"CS is fun"

17
int integers add, subtract, multiply, divide
12345

3.1415
double floating-point numbers add, subtract, multiply, divide
6.022e23

true
boolean truth values and, or, not
false

Java's built-in data types


26
Pop quiz on data types

Q. What is a data type?

27
Basic Definitions

A variable is a name that refers to a value.


A literal is a programming-language representation of a value.
A declaration statement associates variables with a type.
An assignment statement associates a value with a variable.

variables

declaration statement int a, b;


a = 1234;
assignment statements
b = 99;
int c = a + b;
combined declaration
and assignment statement

literals

28
Variables, literals, declarations, and assignments example: exchange values

public class Exchange


A trace is a table of variable values after each statement.
{
public static void main(String[] args) a b t
{
undefined undefined undefined
int a = 1234;
int a = 1234; 1234 undefined undefined
int b = 99;
int t = a; int b = 99; 1234 99 undefined

a = b; This code exchanges


the values of a and b. int t = a; 1234 99 1234
b = t;
a = b; 99 99 1234
}
b = t; 99 1234 1234
}

Q. What does this program do?

A. No way for us to confirm that it does the exchange! (Need output, stay tuned).
29
Data type for computing with strings: String

String data type

values sequences of characters

typical literals "Hello, " "1 " " * " Important note:

operation concatenate Character interpretation depends on context!

operator + character

Ex 1: plus signs "1234" + " + " + "99"


Examples of String operations (concatenation)
operator operator
expression value
"Hi, " + "Bob" "Hi, Bob"
white white
"1" + " 2 " + "1" "1 2 1" space space

"1234" + " + " + "99" "1234 + 99" Ex 2: spaces "1234" + " + " + "99"
"1234" + "99" "123499"
space
characters

Typical use: Input and output.

30
Example of computing with strings: subdivisions of a ruler

public class Ruler


{
public static void main(String[] args)
{ all + ops are concatenation
String ruler1 = "1";
String ruler2 = ruler1 + " 2 " + ruler1; 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
String ruler3 = ruler2 + " 3 " + ruler2;
String ruler4 = ruler3 + " 4 " + ruler3;
[Link](ruler4);
} % java Ruler
} 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1

ruler1 ruler2 ruler3 ruler4


undefined undefined undefined undefined

ruler1 = "1"; 1 undefined undefined undefined

ruler2 = ruler1 + " 2 " + ruler1 1 1 2 1 undefined undefined

ruler3 = ruler2 + " 3 " + ruler2 1 1 2 1 1 2 1 3 1 2 1 undefined

ruler2 = ruler3 + " 4 " + ruler3 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1

31
Input and output
is necessary for us to provide data to our programs and to learn the result of computations.

command-line
Humans prefer to work with strings. arguments

Programs work more efficiently with numbers.

Output
standard output
• [Link]() method prints the given string.
• Java automatically converts numbers to strings for output. Bird's eye view of a Java program

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 [Link]() to convert the strings to integers.

Stay tuned for many more options for input and output, and more details on type conversion.
32
Input and output warmup: exchange values

public class Exchange


{
public static void main(String[] args)
{ % java Exchange 5 2
int a = [Link](args[0]); 2
int b = [Link](args[1]); 5
int t = a;
a = b; % java Exchange 1234 99
b = t; 99
[Link](a); 1234
[Link](b);
}
} Java automatically converts int values to String for output

Q. What does this program do?

A. Reads two integers from the command line, then prints them out in the opposite order.
33
Data type for computing with integers: int

int data type

values integers between −231 and 231−1

typical literals 1234 99 -99 0 1000000 Important note:


operations add subtract multiply divide remainder Only 232 different int values.

operator + − * / %
not quite the same as integers

Examples of int operations

expression value comment Precedence


5 + 3 8 expression value comment
5 - 3 2 3 * 5 - 2 13 * has precedence
5 * 3 15 3 + 5 / 2 5 / has precedence
5 / 3 1 drop fractional part 3 - 5 - 2 -4 left associative
5 % 3 2 remainder
( 3 - 5 ) - 2 -4 better style
1 / 0 runtime error

Typical usage: Math calculations; specifying programs (stay tuned).


34
Example of computing with integers and strings, with type conversion

public class IntOps


{
public static void main(String[] args)
{ % java IntOps 5 2
int a = [Link](args[0]); 5 + 2 = 7
int b = [Link](args[1]); 5 * 2 = 10
int sum = a + b; 5 / 2 = 2
5 % 2 = 1
int prod = a * b;
int quot = a / b;
% java IntOps 1234 99
int rem = a % b; 1234 + 99 = 1333
[Link](a + " + " + b + " = " + sum); 1234 * 99 = 122166
[Link](a + " * " + b + " = " + prod); 1234 / 99 = 12
[Link](a + " / " + b + " = " + quot); 1234 % 99 = 46
[Link](a + " % " + b + " = " + rem);
} Note: 1234 = 12*99 + 46
} Java automatically converts int values to String for concatenation

35
Data type for computing with floating point numbers: double

double data type

values real numbers


. ×
typical literals 3.14159 -3.0 2.0 1.4142135623730951 6.022e23
Typical double values are approximations
operations add subtract multiply divide remainder
Examples:
operator + − * / %
no double value for π.

no double value for
Examples of double operations no double value for 1/3.
expression value
3.141 + .03 3.171
Special values
3.141 - .03 3.111
expression value
6.02e23/2 3.01e23
1.0 / 0.0 Infinity
5.0 / 3.0 1.6666666666666667
10.0 % 3.141 0.577 [Link](-1.0) NaN

[Link](2.0) 1.4142135623730951
"not a number"

Typical use: Scientific calculations.


36
Other built-in numeric types

short data type long data type

values integers between −215 and 215−1 values integers between −263 and 263−1

operations [ same as int ] operations [ same as int ]

float data type

values approximations to real numbers

operations [ same as double ]

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
37
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 also defined for
int, long, and float
double min(double a, double b) minimum of a and b

double sin(double theta) sine function


double cos(double theta) cosine function inverse functions also available:
asin(), acos(), and atan()
double tan(double theta) tangent function
Degrees in radians. Use toDegrees() and toRadians()) to convert.

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)


You can discard your
double PI value of π (constant) calculator now (please).
38
Example of computing with floating point numbers: quadratic equation

±
From algebra: the roots of + + are

public class Quadratic


{ % java Quadratic –3.0 2.0
public static void main(String[] args) 2.0
+
{ 1.0

// Parse coefficients from command-line. % java Quadratic –1.0 –1.0


double b = [Link](args[0]); 1.618033988749895
double c = [Link](args[1]); -0.6180339887498949

// Calculate roots of x*x + b*x + c. % java Quadratic 1.0 1.0


double discriminant = b*b - 4.0*c; NaN + +
double d = [Link](discriminant); NaN
double root1 = (-b + d) / 2.0;
double root2 = (-b - d) / 2.0; % java Quadratic 1.0 hello
[Link]: hello
// Print them out.
[Link](root1); % java Quadratic 1.0
[Link](root2); [Link]
}
}
Need two arguments.
(Fact of life: Not all error messages are crystal clear.)
39
Data type for computing with true and false: boolean

boolean data type Truth-table definitions

values true false a !a a b a && b a || b

literals true false true false false false false false


false true false true false true
operations and or not
true false false true
operator && || ! true true true true

Proof a b !a && b a && !b (!a && b) || (a && !b)


Q. a XOR b?
false false false false false
A. (!a && b) || (a && !b)
false true true false true

true false false true true

true true false false false

Typical usage: Control logic and flow of a program (stay tuned).

40
Comparison operators

Fundamental operations that are defined for each built-in 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

Typical double values are


Examples non-negative discriminant? ( b*b - 4.0*a*c ) >= 0.0 approximations so beware
of == comparisons
beginning of a century? ( year % 100 ) == 0

legal month? ( month >= 1 ) && ( month <= 12 )

41
Example of computing with booleans: leap year test

Q. Is a given year a leap year?


A. Yes if either (i) divisible by 400 or (ii) divisible by 4 but not 100.

public class LeapYear


{
public static void main(String[] args)
{ % java LeapYear 2016
true
int year = [Link](args[0]);
boolean isLeapYear;
% java LeapYear 1993
// divisible by 4 but not 100 false
isLeapYear = (year % 4 == 0) && (year % 100 != 0);
% java LeapYear 1900
// or divisible by 400 false
isLeapYear = isLeapYear || (year % 400 == 0);
% java LeapYear 2000
[Link](isLeapYear); true
}
}

42
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E

2. Basic Programming Concepts


• Why programming?
• Program development
• Built-in data types
• Type conversion

[Link]
Type checking

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.

public class BadCode


{
public static void main(String[] args)
{
String s = "123" * 2;
}
}

% javac [Link]
[Link]: operator * cannot be applied to [Link],int
String s = "123" * 2;
^
1 error

When appropriate, we often convert a value from one type to another to make types match.
44
Type conversion with built-in types

Type conversion is an essential aspect of programming.

expression type value


Automatic
"x: " + 99 String "x: 99"
• Convert number to string for "+".
11 * 0.3 double 3.3
• Make numeric types match if no loss of precision.

[Link]("123") int 123


Explicitly defined for function call.
[Link](2.71828) long 3

Cast for values that belong to multiple types. (int) 2.71828 int 2
• Ex: small integers can be short, int or long. (int) [Link](2.71828) int 3

• Ex: double values can be truncated to int values. 11 * (int) 0.3 int 0

Type conversion can give counterintuitive results


Pay attention to the type of your data.
but gets easier to understand with practice
45
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"

46
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.

short
int, float
long, double

A conversion may be impossible.


• Example: (short) 70000.
• Short values must be between −215 and 215 − 1= 32767 .

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.
First launch of Ariane 5, 1996
47
Example of type conversion put to good use: pseudo-random integers

System method [Link]() returns a pseudo-random double value in [0, 1).

Problem: Given N, generate a pseudo-random integer between 0 and N − 1.

public class RandomInt


{
public static void main(String[] args)
{
int N = [Link](args[0]); String to int (system method)
double r = [Link]();
int t = (int) (r * N);
double to int (cast) int to double (automatic)
[Link](t); % java RandomInt 6
3
}
} % java RandomInt 6
0

% java RandomInt 10000


3184

48
Summary

A data type is a set of values and a set of operations on those values.

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.
49
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E

2. Basic Programming
Concepts
Sections 1.1 and 1.2

[Link]

You might also like