john hurley cs 201 cal state la lecture 2: introduction to computers, programming, and java

52
John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Upload: archibald-rose

Post on 25-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

John HurleyCS 201

Cal State LA

Lecture 2: Introduction To Computers, Programming, and

Java

Page 2: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Computer Hardware

CPU

e.g., Disk, CD, and Tape

Input Devices

e.g., Keyboard, Mouse

e.g., Monitor, Printer

Communication Devices

e.g., Modem, and NIC

Storage Devices

Memory

Output Devices

Bus

Page 3: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Visible, physical elements of the computer. Programmers need to know a little, not a lot, about hardware

Main components:CPU

retrieves instructions from memory and executes themMemory

temporarily stores data and program instructions "volatile" = information is lost if power goes off

Storage Devicesnon-volatile storage; data remains after a power interruption

Communication Devicesdevices that allow computers to communicate with each other

Input and output devicesdevices that let the user communicate with the computer

Components are connected through a subsystem called a bus

Hardware

Page 4: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

SoftwareThe instructions and data that are necessary for

operating a computer

ProgramA software application, or a collection of software applications, designed to perform a specific task

AlgorithmA set of instructions that will solve a problem in a

finite amount of time (Horstmann uses a different definition, but I like this one.)

A program normally implements one or more algorithms

Software

Page 5: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Programmingthe preparation of programs!requires a programming languageFrom Wikipedia:

A programming language is an artificial language designed to express computations that can be performed by a machine, particularly a computer.

Software

Page 6: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Computer executes machine code, also called machine language, which consists of instructions expressed as base 2 numbersdifferent machine languages for different types of

processorsvery few programmers can write machine language (but

hardware engineers who design chips occasionally do)some programming is done in assembly language,

which is a human-understandable set of mnemonic codes that corresponds closely to machine instructionsDifferent for different types of CPUsAssembly language is fun to write, but is only occasionally used

in practical programming today. CS majors study it to understand some fundamental concepts in the field, rather than to use it on the job.

Programming

Page 7: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

LOAD r1, X ; load the variable x into r1

SET r2, 10 ; set r2 to immediate value 10

CMP r1, r2 JMP NEQ, ELSE1 ; If r1 <> r2, then jump to the else part,

; otherwise do the then part

... ; then part 1 (code omitted)

JUMP END1 ; jump over the else part

ELSE1:

... ; else part 1 (code omitted)

END1:

LOAD r1, X ; load the variable x into r1

SET r2, 10 ; set r2 to immediate value 10

CMP r1, r2 JMP NEQ, TEST2 ; if x <> 10 go on to next test

JUMP END2 ; otherwise skip past then part 2

TEST2:

LOAD r1, Y ; load the variable y into r1

SET r2, 20 ; set r2 to immediate value 20

CMP r1, r2

JMP GT, THEN2 ; if y > 20 go on to then part 2

JUMP END2 ; otherwise skip past

THEN2: ... ; then part 2

END2:

Typical Assembly Language Code

Page 8: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Most programmers would take some time to understand the code on the last slide.

Assembly language programming involves manipulation of very small machine operations.

Over time, easier-to-use programming languages have evolved to allow greater programmer productivity

Programming Languages

Page 9: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Memorize this slide!Low level language: few machine instructions per line of programming-language code.

a fancier way to put this: little abstraction from the machine operations

High level language: many machine instructions per line of code

greater abstraction from machine operations Because high-level languages do not directly manipulate machine operations, they can be standardized across different operating systems, and even across different hardware (that uses different sets of machine operations.)Lower level languages often generate programs that run more efficiently (faster or with less memory use) than higher level languagesHigher level languages usually offer better programmer productivity

Programming Languages

Page 10: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Typical assembly language instruction:mov cx,digits

Sets the value held in CPU register cx to the current value of a variable called “digits”

Typical high-level language statement:area = 5 * 5 * 3.1415;

Sets the value of a variable called “area” to 5* 5 * pi

would take many lines of assembly language to do this

Low-level Vs. High-Level

Page 11: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

High level languagesfirst widely-used ones were COBOL and FORTRAN,

used for business and scientific applications. BASIC 1964 used for teaching programmingThousands of other high level languages are or have

been in useAncestry of Java:

ALGOL developed 1950s by a committee of professorsmostly used to describe algorithms, not for actual programs

C 1969 Bell Labs, drew on ALGOLrelatively low leveloriginally designed for programming the UNIX operating

system, but widely used for other softwareC++ 1979 Bell Labs

superset of C, adding support for object-oriented programming

Programming Languages

Page 12: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

ExpenseResources are not free; in programming lingo,

they are said to be expensiveProgrammers’ timeCPU usageMemoryStorage

Minimizing expense is a key part of programminguse as little CPU capacity, memory, storage, etc.

as possibleUse programmers’ time as productively as

possible

Page 13: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

ExpenseHardware has become much less expensive over time.

In 1970, a computer and its peripherals cost millions of dollars and filled a small building. Today most code runs on computers that cost less than $2,000 each.

Programmers in developed countries get paid about the same now in constant dollars as they did 45 years ago

Thus, programmers have become more expensive relative to hardware. The expense of paying us is a much larger part of the total expense of developing software than it was, for example, in 1970.

This favors programming languages and techniques that make programmers more productive, rather than those that execute most efficiently

Page 14: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Java 1995developed at Sun Microsystemseasier to use than C++ in many waysgives up some of C’s low-level capabilitiesapproximately tied with C++ as the most widely

used programming language today Designed to allow identical code to produce the

same results on many different platforms

Java

Page 15: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Main uses of Java today:Used in many web-based applicationsUsed for programming devices like video game consoles, Android phones, BluRay players, etc.Desktop applications that need to be easily ported (moved) to various operating systems. Originally expected to find widespread use in embedded systems (software that runs on computers included in appliances, cars, etc), but this did not pan out

Java

Page 16: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

C#Microsoft’s proprietary answer to Javaproprietary = controlled by a companyVery easily learned by programmers who

already know Java Visual Basic

Another MS proprietary language, descended from both C++ and BASIC

Objective CApple proprietary language, used for Mac

and iOS platform programming

Siblings of Java

Page 17: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

source code = instructions written in a programming language

Assembly language is translated to machine code using an assembler

High level languages are translated using interpreters and or compilersinterpreter translates into machine language at

runtime; no need to store extra filescompiler translates into machine language ahead of

time and stores the executable file: faster at runtime than in interpreter

Programming Language to Machine Instructions

Page 18: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java
Page 19: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java
Page 20: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java
Page 21: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Programming Language to Machine Instructions

Compiler Source File Machine-language

File Linker Executable File

Library Code

Page 22: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Traditional BASIC and JavaScript (language used for writing programs that run in your web browser) use interpreters, as do many newer languages like Python.

C uses compilersJava uses a two-step process that attempts to make

the best of bothMEMORIZE THIS!

Java is compiled before runtime to an intermediate language called Java bytecode

The Java Virtual Machine interprets bytecode to machine language at runtime

All forms of JVM run the same bytecode, but each platform (operating system or hardware type) requires a different type of JVM

Therefore, Java bytecode is analogous to an assembly language for the JVM

Programming Language to Machine Instructions

Page 23: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Main AdvantageJava is highly platform-independent

Write Once, Run AnywhereUsually easy to run the same Java code in

UNIX/OSX/Windows/ Android/Toaster/Antilock Brake System/Whatever

reduces the amount of knowledge the programmer needs to have about the specific platform

adds long-term robustness. Your Java code will still run in Windows 18.7 as long as there is a JVM.

Main Drawbacks:JVM itself uses some memory, CPU capacity, and

other system resourcesAdds one extra step at runtime. Java code often runs more slowly than compiled C++

Pros and Cons of JVM

Page 24: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

24

Statements

A statement represents an action or a sequence of actions. This is different from the usual English meaning of the word “statement”

Example: System.out.println(“Hello, World!");

prints the message “Hello, World!”Every statement in Java ends with a semicolon (;).

Page 25: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

25

Variable and Constant Declarations

Programs often use variables and constantsYou already know these concepts from algebraYou must tell the computer to set aside memory space for any variable or constant you useint x = 0;

finds space to store an integer, names it x, and sets the value of x to 0

Page 26: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Memoryvolatile = data is normally lost when power lost

(reboot or power interruption)every location in memory has a numeric addressall information is measured in bits

a bit is a unit of information, not a physical device.ooften corresponds to a physical transistor, but

programmers don’t need to think about this.obut a bit can be conceptualized as a switch that

is either on or offovalues of single or multiple bits are conveniently

represented as base 2 (binary) numbersocan also be interpreted as true / false

Memory And Data

Page 27: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Base 2

Decimal Binary

0 0

1 1

2 10

3 11

4 100

5 101

6 110

Decimal Binary

7 111

8 1000

9 1001

15 111116 10000

Page 28: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

You do not have to become a whiz at base 2 arithmetic,but you do need to develop basic familiarity with it

Base 2 math in this course is intended tomake the point that programming is just a fancy way

to flip billions of switchesease the learning curve for later courses in which

you will need to understand binaryThere may be a few easy questions on base 2

arithmetic on the quizzes and/ or exams. They will be similar to the examples below.

Bits

Page 29: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

2919/04/23

Binary Arithmetic Rules0 + 0 = 00 + 1 = 11 + 0 = 11 + 1 = 10 1+1+1 = 11

Page 30: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

01 + 01 = 1011 + 11 = 110101 + 101 = 10101000 + 1 = 10011000 + 11 = 10111111 + 1 = 10000

11 – 10 = 1100 – 10 = 10101 – 11 = 10

Binary Arithmetic

Page 31: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

1 byte = 8 bits28 = 256, so the value of 1 byte ranges from

00000000 to 11111111 binary = 0 to 255 decimal1 byte is usually the minimum amount of information

that you can manipulateTerms like kilobyte and megabyte refer to quantities

of bytes in units that are powers of 2 close to the decimal numbers implied in the names, 1K = 1024 bytes; 1meg = 1048576 bytes

Most of the time, the actual storage units are invisible to the programmer. For example, you will usually deal with an integer without worrying about the fact that the computer sees it as 4 bytes

Bytes

Page 32: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Every data item (variable, constant, or even a literal, such as the integer 3 or the string “Godzilla”) has a specific data type.

Each type of data is stored with a specific amount of memory and handled differently by the compiler

Thus, you must think carefully about the type of every piece of data you use.

•a character takes less space to store than an integer

•you can’t find the product of two variables unless they are both numbers

•If you divide one integer by another and store the quotient as an integer, you may lose information. It may not be good enough to say that 5 / 4 = 1

Data Types

Page 33: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Storage affects the possible values for a piece of data. Java uses 4 bytes = 32 bits to store the value of an integer

The (complex) method for tracking the sign uses one bit.

231 = 2147483648a Java integer has possible values from -2147483648 to

+2147483647 2147483647 + 1 = garbageMemorize this: “the minimum value for a Java integer is approximately negative 2 billion. The maximum value is approximately positive 2 billion.”

Data Types

Page 34: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Variables and Constants

You must tell the JVM in advance when you will use a variable or constant

Must specify what kind of data the value will use

JVM knows how much (expensive) memory to use to track the value

Example: int answer=1;

creates a variable called answer, sets aside space to store it, sets the initial value to 1

Page 35: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Data Types

Primitive Data Typesprimitive = built in to the programming

language as a basic building blockMany other data types are built into Java,

but are made up of primitive types plus methods

Later you will learn how to build your own data types using primitive and other built-in types as building blocks

Page 36: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Numeric Data Types Name Range Storage Size

byte –27 (-128) to 27–1 (127) 8-bit signed

short –215 (-32768) to 215–1 (32767) 16-bit signed

int –231 (-2147483648) to 231–1 (2147483647) 32-bit signed

long –263 to 263–1 64-bit signed (i.e., -9223372036854775808 to 9223372036854775807)

float Negative range: 32-bit IEEE 754 -3.4028235E+38 to -1.4E-45 Positive range: 1.4E-45 to 3.4028235E+38

double Negative range: 64-bit IEEE 754 -1.7976931348623157E+308 to -4.9E-324 Positive range: 4.9E-324 to 1.7976931348623157E+308

Page 37: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

37

Floating Point Types

“Floating point types” inlude the types float and double

Internal representation of floating points types includes an exponent, much as in scientific notation

These types store values with limited precision, essentially rounding to the closest value they can hold

double doesn’t just hold a larger range of values than float, it also provides greater precision

If you want to learn more about this, seehttps://en.wikipedia.org/wiki/Floating_point_type

Page 38: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

38

Numeric Data Types

Tradeoffs in choosing numeric data typesMinimize resource usage; use smallest type that

will hold the values you expect to useMinimize risk of error; pick safest choiceMost of the time, programmers use int for

integers and double for floating point numbersUse long if the value may be larger than an int

can storeRarely use byte or short

Page 39: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

39

Numeric Data Types

Declare a double:double x;

declare a double and set its value to 1double x = 1.0;double x = 1d;

Page 40: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

40

Methods

Procedures for performing particular tasksJava methods are equivalent to functions, subroutines, or procedures in other languagesAll you need to understand right now about methods is how to see what is inside one and what isn’t. Most of our code will be inside methods.A method:

public int get Product(int x, int y) {return x * y;

}

Page 41: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

41

Classes

A class is a template or blueprint for objects. You will learn to understand classes in more depth later in this course, but all of our work in this class will be done inside classes.For now, understand that a program is defined by using one or more classes.

Page 42: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

42

ClassesClasses often (not always) model real-world entities or abstractions that already exist outside the program

A Ship object might have data variables including weight, country of registration, and engine displacementprocedures (methods/ functions/ subroutines) including accelerate, show speed, drop anchor, fire cannon, prepare to be boarded, sink

A Rectangle object might have three data variables that represent coordinatesmethods to calculate area and perimeter and to determine whether a given coordinate is inside the rectangle

Page 43: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

43

ObjectsAn object is a self-contained entity that consists of both data and procedures to manipulate the data. In Java and most (not all) other object-oriented languages, objects are instances of classes (think Plato.)Objects may have values for the variables defined in the class. Multiple objects of the same class have the same variables, but the actual data (value of the variables) may be different, in the same way that all ships have weights but there may be no two ships with the same weight.

Accordingly, running the same methods for different objects of the same class may produce different results.

Page 44: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

44

main()The main() method is the starting point for the flow of control in the program. The JVM executes the application by invoking (running) the main method.For the time being, all our classes will contain main() methods main() often calls other methods, including ones that are in other classes main() looks like this:

 public static void main(String[] args) { // Statements;}

Page 45: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

45

System.out.println

The simplest way to show outputBy default, prints to the command console

System.out.println("Hello, World!");prints the message “Hello, World!”

System.out.println(i) prints the value of a variable named i

System.out.println("i = " + i);prints the literal text "i =" followed by the value of I

The + means "concatenate the next item to this output," ie "add the value of the variable i to the end of the text in the quotes"if the value of i is 1 at the time the statement executes, prints “i = 1”

Page 46: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

46

CommentsIgnored by the compiler and JVMUsed for documentation intended for programmers or

other people involved in development Single line comment: A line comment is preceded

by two slashes (//) in a line. The rest of the line becomes a comment.

Multiline comment: A paragraph comment is enclosed between /* and */ in one or multiple lines.

javadoc comment: javadoc comments begin with /** and end with */. They are used for documenting classes, data, and methods. They can be extracted into an HTML file using JDK's javadoc command.

Page 47: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Later in the course, we will use Eclipse, an Integrated Development EnvironmentIDE = a software package that provides tools for

programmingFor now, we will run programs from a command lineUse the lab computers in class, but get the latest

release of the Java Development Kit for your homework. Allow plenty of time for installation in case things go wrong!

See Supplement I.B for installing and configuring JDKSee Supplement I.C for compiling and running Java

from the command window for details: www.cs.armstrong.edu/liang/intro8e

Mac users: OSX has a version of the JDK preinstalled. It may not be current, but it should work fine for this class

Running A Java Program

Page 48: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Java Standard Edition (J2SE)J2SE is used to develop client-side standalone

applications or applets. We will use this edition.Java Enterprise Edition (J2EE)

J2EE can be used to develop server-side applications such as Java servlets and Java ServerPages. It is OK to get this one, but the download is bigger and we won’t use the additional functionality.

Java Micro Edition (J2ME). J2ME can be used to develop applications for

mobile and small embedded systems

JDK Versions

Page 49: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Java source code is stored in plain text files with .java file name extension. You can save them on a flash drive or your server space (ask IT, not me, where that is!) or email them to yourself.

For the time being, write your code with a plain text editorRecommended for Windows: Notepad++ or Geany.

Notepad, TextEdit, etc. will work too, but Notepad++ is better. You can use a word processor, but if you do you will soon realize why I don’t recommend it.

Save as plain text using extension .java. If your editor contains a “save as java source” option, that will work fine, too.

Running A Java Program

Page 50: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Instructions for running a Java program from the command line are in Section 1.8 of the book

Key steps: Add JDK bin directory to path, e.g.

set path=c:\java\jdk1.7.0\binBe *careful* editing your path!

Open a command prompt and navigate to the folder where you saved the file

Type javac filename.java Compiles Java source to Bytecode for example, if the program file is called Hello.java, type

javac Hello.java Notice that there is now a file called filename.class, eg Hello.class. This file contains the bytecode

Type java classname Runs the JVM with the bytecode as input for example, java Hello If you get a NoClassDefFound error, type set classpath= then try again

Running A Java Program

Page 51: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

NoClassDefFoundErrors are usually caused by incorrect settings for the classpath variable.

More instructions and an explanation of classpath are at

http://en.wikipedia.org/wiki/Classpath_(Java)

For the time being, just navigate to the directory where the java file is before you compile and run

NoClassDefFoundErrors

Page 52: John Hurley CS 201 Cal State LA Lecture 2: Introduction To Computers, Programming, and Java

Start with this code:

public class Skeleton{public static void main(String[] args){

// early in the course, all your code will go inside main()

} // end main method} // end class

Skeleton Java class