what’s in ics.h22 2. java –useful because commonly used –great example of an object- oriented...

34
What’s in ICS.H22 2. Java Useful because commonly used Great example of an object-oriented language • Object-oriented languages encourage code reuse and good code design => Code tends to be more reliable Java is also “strongly typed” so it’s harder to make mistakes Learning how computers work: how programs are compiled and executed. 1. Algorithms and Data Structures From simple to more complex All very fundamental and useful You practice algorithmtic thinking… 1+2: Learning algorithms in practice: Coding and executing them in java

Post on 21-Dec-2015

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

What’s in ICS.H222. Java

– Useful because commonly used

– Great example of an object-oriented language

• Object-oriented languages encourage code reuse and good code design

=> Code tends to be more reliable

• Java is also “strongly typed” so it’s harder to make mistakes

– Learning how computers work: how programs are compiled and executed.

1. Algorithms and Data Structures– From simple to more

complex– All very fundamental and

useful– You practice algorithmtic

thinking…

1+2: Learning algorithms in practice: Coding and executing them in java

Page 2: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Why Java ? • Java is an elegant, powerful programming

language• simpler than other object-oriented languages [e.g., C++]• Java is the basis of other modern programming languages

[e.g., C#]

• Java is platform independent --- write once run everywhere

• Java supports multiple platforms (Unix, Windows, Mac), multiple types of devices (desktops, PDAs, phones, embedded devices)

• Java has good support• good multimedia, graphics packages• good client-server and network support (applet, serverlet)• good, free Integrated Development Environments (IDE)

Page 3: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Java Programming Language: Designers

Bill Joy• BSD Unix guy from Berkeley

• founded Sun Microsystems (early 80s)

• “the network is the computer” (a little ahead of its time)

– target workstation market

• missed the boat on PC revolution, retreated to Aspen, Colorado

James Gosling• early fame as the author of

“Gosling Emacs” (killed by GNU)

• then onto Sun’s “NeWS” window system (killed by X)

• lesson: keeping things proprietary is kiss of death

Page 4: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Java Programming Language: History

• Joy and Gosling joined force, Sun subsidiary, FirstPerson, Inc. (1992)

• target consumer electronics: PDAs, appliances, phones, all with cheap infra-red kinds of networks

• need a language that’s small, robust, safe, secure, wired– started working on C++--– soon gave up hope, decided to start from scratch

• Bad luck (again)• bad luck: a little ahead of time

– PDAs died with the demise of Apple Newton– switched to interactive TV (ITV)– the resulting language was called “Oak”– then ITV died too

• good luck (finally)– the net exploded in 1993– Oak became Java, rest is history!

Page 5: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Learning Java

• just like learning any new language– syntax: “new words”– grammar: how to put them together– programming: telling a coherent story– library: use plots already written

• initially needs efforts, but pays off in the end !

Page 6: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Machine Languages

The “brain” of a computer is its Central Processing Unit (CPU)

A CPU can understand only very basic instructions,

- e.g., store a given value at a memory location, do some arithmetic operations, compare two values, start to execute the instruction at another location

The set of instructions of a CPU form the machine language of the CPU

Intel PentiumIBM PowerPC 750 for iMac

Page 7: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Machine Languages Machine languages, or the instructions understood by computers, are represented by numbers

for example, for Intel x86 (which includes Pentium), the numbers 10110000 01100001give the instruction: copy number 97 to the processor register storage named ah.

Each type of CPU has its own specific machine language (why?)

Early programmers wrote programs using machine languages

- the first programmer is Ada Byron (Lady Lovelace)

Page 8: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Higher-Level Programming Languages

• Other levels of programming languages were created to satisfy different objectives, e.g., make it easier for a human being to read/write programs:– assembly languages– intermediate languages– high-level languages

Page 9: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Assembly Languages

movl (%edx,%eax), %ecx

movl 12(%ebp), %eax leal 0(,%eax,4), %edx movl $nodes, %eax movl (%edx,%eax),

%eax fldl (%ecx) fsubl (%eax) movl 8(%ebp), %eax leal 0(,%eax,4), %edx movl $nodes, %eax movl (%edx,%eax),

• Assembly language or simply assembly is a human-readable notation for the machine language

it’s much easier to remember:

movl %al, 97 than 10110000 01100001

Example assembly code fragment

Page 10: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

High-Level Programming Languages

int celsiusTemp = 32; double fahrenheitTemp;

fahrenheitTemp = celsiusTemp * 9.0 / 5.0 + 32;

if (fahrenheitTemp > 100) System.out.println (“Hot !”);

else System.out.println (“OK !”);

• A high-level programming language enables a programmer to specify, in a high level (close to natural language), what data a computer will act upon, how these data will be stored, and what actions to take under various circumstances

• A high-level language is independent of CPU

Example Java Code fragment

Page 11: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Programming Languages• A program written in a high-level language must

be translated into machine language before it can be executed on a particular type of CPU

• A compiler is a software tool which translates source code into a specific target language– typically, that target language is the machine language

for a particular CPU type

sourcecode

machinecode

compiler

c, c++ intel x86gccHelloWorld.c HelloWorld.exe

e.g.,

Page 12: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Java Translation• To be platform independent, Java cannot use the

previous approach

• Java introduces an intermediate language called bytecode– Java bytecode is not the machine language for any

traditional CPU, but a virtual machine– the Java compiler translates Java source code (.java

files) into bytecode (in .class files)– therefore the Java compiler is not tied to any particular

machine– Java is thus considered to be architecture-neutral

Page 13: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Java Execution• To execute a Java program, another piece of

software called an interpreter , translates between bytecode and the machine language– an interpreter is specific to a specific machine language

– the interpreter understands java bytecode, and then issues instructions in the machine language for which it is written

– we also say that an interpreter provides a java virtual machine (JVM)

• Another approach is to have a “just in time” (JIT) compiler which translates from bytecode to machine code on the fly, while interpreting it

Page 14: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Java Translation and ExecutionJava source code

Java compiler

Java interpreterfor Windows

Machine code

JIT compiler

Java bytecode

Java interpreterfor Mac

Page 15: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Related Topic: Programming Errors…

A program can have three types of errors• The compiler will find problems with syntax and

other basic issues (compile-time errors)– If compile-time errors exist, an executable version of

the program is not created

• A problem can occur during program execution, such as trying to divide by zero, which causes a program to terminate abnormally (run-time errors)

• A program may run, but produce incorrect results (logical errors)

Page 16: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Java Programming: The Edit/Compile/Run Loop

• Programming in Java consists of three tasks– edit java source code (.java

files)– compile java source code to

generate bytecode (.class files)

– execute/run/test bytecode using an interpreter

Page 17: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

An Sample Java Program

//==========================================================// // HelloWorld.java// // Author: Richard Yang// // Class: HelloWorld// // ---------------------------------------------------------// This program prints a string called "Hello World!”////==========================================================

public class HelloWorld{ public static void main(String[] args) { System.out.println("Hello World!"); } // end of method main} // end of class

Page 18: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Comments• Two types of comments in Java

• single-line comments use //… // this comment runs to the end of the line

• multi-lines comments use /* … */

/* this comment runs to the terminating symbol, even across line breaks */

• Comments are ignored by the compiler:– used only for human readers (i.e., inline

documentation)

– they should be included to explain the purpose of the program and describe processing steps

Page 19: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Identifiers

• Identifiers are the words that a programmer uses in a program

• An identifier can be made up of letters, digits, the underscore character (_), and the dollar sign ($)

• An identifier cannot begin with a digit (why?)

• Java is case sensitive, therefore Total and total are different identifiers

Page 20: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Three Types of Identifiers

1. Identifiers chosen by ourselves when writing a program (such as HelloWorld)

2. Identifiers chosen by another programmer, so we use the identifiers that they chose (e.g., System, out, println, main)

public class HelloWorld{ public static void main(String[] args) { System.out.println(“Hello World!”); }}

Page 21: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Identifiers: Reserved Words

3. Special identifiers called reserved words that already have a predefined meaning in the Java language- a reserved word cannot be used in any other way

abstractbooleanbreakbytebyvaluecasecastcatchcharclassconstcontinue

defaultdodoubleelseextendsfalsefinalfinallyfloatforfuturegeneric

gotoifimplementsimportinnerinstanceofintinterfacelongnativenewnull

operatorouterpackageprivateprotectedpublicrestreturnshortstaticsuperswitch

synchronizedthisthrowthrowstransienttruetryvarvoidvolatilewhile

Java revered words: they are all lowercase!

Page 22: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Java Program Structure

• In the Java programming language:– a program is made up of one or more classes– a class contains one or more methods

• Java application must always contain a method called main

– a method contains program statements

Page 23: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Java Program Structure: Class

public class HelloWorld

{

}

// comments about the class

class headerclass header

class body starts with a left brace { class body starts with a left brace { and ends with a right brace }and ends with a right brace }

comments can be added almost anywherecomments can be added almost anywhere

class name is anclass name is anidentifier; conventionidentifier; conventionwe follow: capitalizewe follow: capitalizeeach English wordeach English word

Page 24: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Structure of a Java Class

public class Classroom

{

}

int min_capacity = 0;int max_capacity = 100;int chairs = 30;…

// instance variables

// methods

public int addStudents (int students) { … }public int addChairs (int chairs) { … }…public static void main (String[] args){ … }

Page 25: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Java Method and Statements

• Methods– building blocks of a class– each method name is an identifier, e.g. “addStudents”

• convention we follow: a method name starts lower case, with each additional English word capitalized (e.g., main, doMyJob )

– the main method• each Java application must have one

• all programs start by executing the main method

– braces are used to start ({) and end (}) a method

• Statements– every statement must end in a semicolon ;

Page 26: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Classes and Methods

• Methods and classes are language constructs to help organize a program– a method “organizes” a sequence of statements

• thus we can use a single method to refer to a bunch of statements

– a class “organizes” a collection of methods (and data)

• Division of tasks into classes and methods supports object-oriented programming and creates good abstraction boundaries between different tasks and objects

Page 27: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Classes and Methods Provide Abstraction

• In the jargon of program design, they are structures which provide abstraction

• The objective of abstraction is to help programmers to hide (or ignore) the right details at the right time

• Why abstraction– a human being can only manage seven (plus or

minus 2) pieces of information at one time• if we group information into chunks, for example, by

organizing complex software carefully into methods and classes, we can write more complex software

Page 28: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Methods and Classes

• A method provides an abstraction for a sequence of statements– initially, a method helps a programmer to refer to a a sequence of

statements which she may reuse– more generally, a method defines a service

• a method takes input (parameters), performs some actions, and (sometime) returns a value

– we invoke a method (call its service) and specify input/parameters

• A class provides an abstraction for objects with some common behaviors/services which we can tell them to perform for us– the services/behaviors provided by an object are defined by the

methods in the class that defines the object– we create objects from its class definition: class serves as a

blueprint

Page 29: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

29

Example

• System.out is an object created from the PrintStream class

• Example: invoking the println method of the System.out object:

System.out.println ("Whatever you are, be a good one.");

Objectcreated

fromPrintStream

class

methodInformation provided to the method

(parameters)dot

Page 30: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Declaring Object Reference Variables• In the general case, we need to first create objects

– pre-created objects such as System.out are rare

• To “keep track” of created objects, we need variables to refer to the created objects– variables are identifiers

• A variable can be used to refer to different objects• To avoid mixing different types of objects, we should

specify the type of objects that a variable can refer to; thus we need to specify the type of a variable: <Type> <variableName>;

Page 31: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Declaring Object Reference Variables

• Example:String title;

where String is a predefined class in Java; we also call title an object reference variable

• No object has been created with the above declaration of a variable

• The object itself must be created separately

Page 32: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Explicitly Creating Objects• We use the new operator to create an object

title = new String (“Java Software Solutions");

This calls the This calls the constructorconstructor method of class method of class StringString,,which is a special method that sets up the objectwhich is a special method that sets up the object

(every class must have a constructor method)(every class must have a constructor method)

• Now the variable title refers to an instance of String object

title “Java Software Solutions"

Page 33: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Explicitly Creating Objects

• “new” operator in general:

<varName> = new <className> ([<params>]);

This calls the This calls the constructorconstructor method of class <className> method of class <className>which (optionally) takes some parameters <params>which (optionally) takes some parameters <params>

• Now the variable <varName> refers to an object which is an instance of class <className>

<varName> Object of class <className>,constructed using parameters <params>

title = new String (“Java Software Solutions");

Page 34: What’s in ICS.H22 2. Java –Useful because commonly used –Great example of an object- oriented language Object-oriented languages encourage code reuse and

Use Methods of Objects

• Once an object has been instantiated, we can use the dot operator to invoke its methods, e.g.,

count = title.length();

• This procedure call invokes method “length” of class String, because “title” is a variable which refers to an object which is an instance of class String.

• Saying it another way: “title” is a variable of “type” String

• Methods (e.g. method “length” of class String) can return values(Here the return value is assigned to variable “count”)

title = new String (“Java Software Solutions");

title “Java Software Solutions"