Top Banner
COP2800– JAVA PROGRAMMING Dr Delessy-Gassant
64
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Lecture 1 introduction to_computersb(2)

COP2800– JAVA PROGRAMMINGDr Delessy-Gassant

Page 2: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO COMPUTERS

What is a computer? A computer is an electronic device,

operating under the control of instructions (software) stored in its own memory

A computer contains many electric, electronic, and mechanical components known as hardware:

Input devices Output devices System unit Storage devices Communication devices

Page 3: Lecture 1 introduction to_computersb(2)

THE COMPONENTS OF A COMPUTER

Page 4: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO COMPUTERS

The system unit typically includes: Processor

The brain Memory

Stores data temporarily

Drive bays Hard disks,

CD / DVD drives Power supply unit Sound cards Video cards

Page 5: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO COMPUTERS

The processor, a.k.a. central processing unit (CPU), interprets and carries out the basic instructions that operate a computer. Made of billions of transistors (in 2010) Transistor = electronically controlled switch, made form

semi-conductor materials It contains:

a control unit: coordinates most of the operations in the computer

an arithmetic logic unit (ALU) performs arithmetic, comparison,

and other operations Registers

Small amount of storage

Page 6: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO COMPUTERS

The main memory, a.k.a. RAM: content is volatile

(will be erased when the system is shut down),

but access time is faster

used as working storage by the CPU

Page 7: Lecture 1 introduction to_computersb(2)

1-7

COMPUTER SYSTEMS: HARDWAREMAIN MEMORY

Commonly known as random-access memory (RAM)

RAM contains: currently running programs data used by those programs.

RAM is divided into units called bytes. A byte consists of eight bits that may

be either on or off.

Page 8: Lecture 1 introduction to_computersb(2)

1-8

COMPUTER SYSTEMS: HARDWAREMAIN MEMORY

A bit is either on or off: 1 = on 0 = off

The bits form a pattern that represents a character or a number.

Each byte in memory is assigned a unique number known as an address.

RAM is volatile, which means that when the computer is turned off, the contents of RAM are erased.

Page 9: Lecture 1 introduction to_computersb(2)

1-9

COMPUTER SYSTEMS: HARDWAREMAIN MEMORY

A section of memory is called a byte.

A section of two or four bytes is often called a word.

Main memory can be visualized as a column or row of cells.

0x000

0x001

0x003

0x002

0x004

0x005

0x006

0x007

A byte is made up of 8 bits.1 0 1 0 1 0 1 0

Page 10: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO COMPUTERS

• The Von Neumann architecture• Conceptual model that inspired almost every

machine today• >The program is stored as general data

in memory

ALU

Control

Unit

Registers

CPU

Memory Input devices

Output devices

commands: read, write

data, instructio

ns

Page 11: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO COMPUTERS The fetch-execute cycle:

Once a computer has been powered on it performs a continuous cycle of the following:

1. Fetch next instruction from memory2. Decode the instruction3. Possibly fetch data from memory4. Execute the instruction5. Store results back to memory

ALU

Control

Unit

Registers

CPU

Memory

Input devices

Output devicescommands

: read, write

data, instructio

ns

Page 12: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO COMPUTERS

The electronic circuits of a computer can recognize and execute a limited set of simple instructions, the machine’s instruction set

Instructions carried out by a computer are simple: Arithmetic or logic operations

Ex: addition, multiplication, XOR

Operations that move data from memory/peripherals to the CPU and the other way around

display a movie on a screen, accept input from the keyboard

Page 13: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO COMPUTERS

Data representation Computers are digital:

data is stored in terms of discrete values The binary system uses two unique digits

(0 and 1) Bits and bytes

Even instructions are eventually stored in terms of 0’s and 1’s

Machine instructions encoded in terms of 0’s and 1’s constitute the machine language

Demo: http://www.onlinedisassembler.com/

Page 14: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO COMPUTERS What is a program?

A series of instructions given by a programmer to a computer in order to perform a task

Tasks carried out by computers are more and more complex. Examples of useful programs?

But you don’t want to program using machine language! Too tedious! Cf. OllyDgb

Programming languages make it easier for programmers to write programs They define nice (intuitive) ways to talk to a

computer

Page 15: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO COMPUTERS

Programming languages are classified into 3 levels: Machine language Assembly languages

more intuitive to the programmer, but still (low level) i.e., close to machine language

Cf. http://www.onlinedisassembler.com/ High-level languages

More user-friendly to the programmer Includes abstractions such as loops, switches, … Ex: Java, C/C++, C#, and many more

Page 16: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO COMPUTERS

Programming languages are of 2 categories: Compiled:

1. The source code (high-level language instructions) is translated into machine code by a compiler

2. The machine code is saved in an executable file3. The executable file is run faster Ex: C/C++

Interpreted:1. The source code (high-level language instructions) is saved on

the disk2. An interpreter is executed, and the source code is brought to

memory. The interpreter translates, on-the-fly, the source code into machine code, thus executing the high level program

slower, but more portable Ex: Java, C#, Python

Page 17: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO COMPUTERS

Java is a special case: It uses a mix of

compilation and interpretation:

1. The source code is compiled into an intermediary language, the bytecode, which is saved on the disk

2. The bytecode is brought to memory and interpreted at runtime

Editor

Compiler

Interpreter

Source code (*.java files)

Bytecode (*.class files)

Program output, error messages

Your program will not be perfect the first time (errors) Practically, programming is often a cycle

The programmer writes some code in the

Java language

and saves its .java files to

the disk

Java instructions

are translated in

an intermediate format and

saved into .class files on the

disk

The .class files are

brought in memory, and

each instruction from the

bytecode is translated

into machine language

that is run

Page 18: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO COMPUTERS

Other characteristics of Java: Popular Object-oriented Simple Portable Robust/secure

Page 19: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO COMPUTERS

In the labs, we use a powerful tool: Netbeans Editor Compiler Interpreter And more…

Page 20: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO COMPUTERS

Example of Java applications Web applications

Server side >Blackboard (parts)

Client side (Applets embedded in web pages) >Blackboard widgets

Enterprise applications Desktop applications

With GUI (Graphic User Interface) >Netbeans

Console applications Apps for mobile devices

on Blackberry, Android, palm, and maybe some day on iPhone?

Page 21: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO JAVA APPLICATIONS

(One of )the simplest Java program:

Page 22: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO JAVA APPLICATIONS

First remarks: Java is case-sensitive

‘Class ‘ is not the same as ‘class’ Java does not care about the colors, or the

appearance of the source code Colors are added automatically by Netbeans to

help the programmer read the text

Page 23: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO JAVA APPLICATIONS

Comments Are portions of the source code that will be

ignored by the compiler not translated in bytecode

Used for documentation purposes > in this class, you are encouraged to comment your code

(part of the grade for an assignment)

Page 24: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO JAVA APPLICATIONS

Comments 2 kinds of comments:

1. Comments that runs on one single line Start with ‘//’ and end at the end of the line Typically makes a particular part of your code easier to understand

2. Comments that can run on multiple lines Start with ‘/*’ and end with ‘*/’ Used to make your code easier to use, typically by other

programmers Used for administrative purposes, e.g. name of the author,

assignment number, …

Page 25: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO JAVA APPLICATIONS

This is a simple

statement

This is a composite statement

This is another

composite statement

Java programs consist in a series of statements

i.e. an instruction written in a high-level language Simple statements

Typically end in ‘;’ Composite statements contain blocks of other

statements Nested statements This is how programs are recursively constructed!

Examples of statements Each type of statement has a precise syntax

Page 26: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO JAVA APPLICATIONS

Blocks Blocks consist of successive statements contained

between an opening and a closing brace Example of blocks

Everything between ‘{‘

and ‘}’ makes up a block

This is another block

Page 27: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO JAVA APPLICATIONS

Java is an object-oriented language Advanced java programmers manipulate objects Prior to manipulating any object, a class for this

kind of object must be defined You can subsequently instantiate as many objects of that

class that you want

The outermost statement of a java source file is a class definition

This statement is

a class definition

Page 28: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO JAVA APPLICATIONS

Simple class definition Type reserved words ‘public class’ Choose and type a name (a.k.a. identifier) for your

class E.g. SimplestClassEver

Type an opening brace and a closing brace

Page 29: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO JAVA APPLICATIONS

Choosing a valid identifier (=name) An identifier is composed of a sequence of:

Unicode letters (include letters from non-english alphabets),

digits, underscores (‘_’) dollar signs (‘$’)

An identifier cannot begin with a digit An identifier cannot be a reserved word

(e.g. ‘class’, ‘public’, ‘static’, …)

Page 30: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO JAVA APPLICATIONS

This statement is the definition of the main

method of the application

Every application needs a point of entry identifies the first instruction to be executed

In Java, the point of entry is the main method

Methods have a signature to differentiate them from other methods

Methods have a body Succession of statements that must be carried out when

the method is executed Methods will be discussed soon in more detail…

This is the signature of the main method Everything inside this block

is the body of the main method

Page 31: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO JAVA APPLICATIONS

How to write a main method1. Type the main method signature (always the same)2. Type the ‘{‘ and ‘}’3. Insert your statements within the body of the main method

Page 32: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO JAVA APPLICATIONS

Your first practical statement: basic output uses the ‘System’ class from the core library to print a

message to the screen The message must be between double quotes! It is provided as an argument to the ‘println’ method of the

System output stream. How do you write a basic output statement

1. Type the call to ‘println’ from the output stream of the System object:

System.out.println();

2. Insert you message between the braces, 3. Message must be surrounded by “”

Page 33: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO JAVA APPLICATIONS

Your first practical statement: basic output The message cannot include ‘”’ sign (double

quote) or the single quote sign What if your message needs to include ” or

‘? precede it with the escape character ‘\’ Ex: In order to print the message: “I will be there,” he said

Page 34: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO JAVA APPLICATIONS

Final remarks Code formatting does not matter

Indentation does not matter to Java (But it does matter to a human readers)

=

Page 35: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO JAVA APPLICATIONS

Final remarks Code formatting does not matter

White spaces (space, tabulations, blank lines..) can be used interchangeably

=

Page 36: Lecture 1 introduction to_computersb(2)

INTRODUCTION TO JAVA APPLICATIONS

Summary Comments are omitted by the compiler Simple and composite statements are used to recursively build

program source files The outermost statement of a source file is a class definition If your class needs to do something, it needs a point of entry,

the main method, and inside this method at least one practical statement (e.g. message printing)

Page 37: Lecture 1 introduction to_computersb(2)

VARIABLES

Concept of variable computers, (and more precisely,

programmers) needs to organize the data to be remembered

a variable is a named memory location that is used to hold temporary data in a program

facility for storing temporary data

Page 38: Lecture 1 introduction to_computersb(2)

VARIABLES

A variable is characterized by: a name

The programmer can choose any identifier, using rules (cf. Lect 1)

Include alphabetic Unicode characters, digits, underscore, and ‘$’

The first character cannot be a digit, The identifier cannot be a reserved word.

a value a bunch of 0s and 1s stored in this memory location can be changed during the execution of the program

a type helps java remember how the programmer wants to

interpret these 1s and 0s

Page 39: Lecture 1 introduction to_computersb(2)

VARIABLES

In Java, there are 8 primitive data types byte

raw 0s and 1s you won't need to interpret the data

Use cases: data just needs to be transferred onto the network, or to a file...

short, int, long you want to interpret the 0s and 1s as integers,

e.g. -2, 0, 4555, -3245, ... Use cases: you want to store the number of

sales in your shop today, the number of students in a class,…

Page 40: Lecture 1 introduction to_computersb(2)

VARIABLES

In Java, there are 8 primitive types float, double

you want to interpret the 0s and 1s as real numbers, for which the accurate value is not important

Use cases: you want the computer to remember the surface area of a house, e.g. ~1545.86 sq.ft.

Counter example: the amount of money in your customers 'accounts (You want a precise value!)

Warning: When using float and double, round-off errors may accumulate!

char You want to interpret the 0s and 1s as characters uses: You want to store students' middle initials

Page 41: Lecture 1 introduction to_computersb(2)

VARIABLES

In Java, there are 8 primitive types boolean

You want the computer to interpret the 0s and 1s as one of the 2 values: 'true' or 'false'

Use cases: You want to store whether or not a member of your club has paid his membership this year

Page 42: Lecture 1 introduction to_computersb(2)

VARIABLES Several java types are used for representing integers.. id for real numbers… How do I choose ??

It depends on the range of values that you want to represent…

while saving memory space, i.e, reducing the memory footprint of your program

For real numbers, precision is also important: ~16 decimal digits for double vs ~7 decimal digits for float

Page 43: Lecture 1 introduction to_computersb(2)

VARIABLES Several java types are used for representing integers.. id for real numbers… How do I choose ??

It depends on the range of values that you want to represent while saving memory space, i.e, reducing the memory footprint

of your program Warning: if a large number is stored in a location that is too

small, there is an overflow! no error is reported! An incorrect number is stored!

For real number, precision is also important

Page 44: Lecture 1 introduction to_computersb(2)

VARIABLES

Ex: number of sales per day in all Walmart stores?

Number of sales per day in your local computer shop?

Page 45: Lecture 1 introduction to_computersb(2)

VARIABLES

String is not a primitive data type We will see soon that it is are pre-defined

class Strings represent sequences of

characters But because they are so useful, we are

going to use them early

Page 46: Lecture 1 introduction to_computersb(2)

VARIABLES

Categories of variables In Java, there are 4 categories of variables

Local variables: Defined in a block In the first part of this class, we concentrate on local

variables only! Instance variables, (a.k.a. non-static fields)

Defined within a class, with a different value for instance of the class

Class variables (a.k.a. static fields) Defined within a class

Formal parameters Defined within a method

Page 47: Lecture 1 introduction to_computersb(2)

VARIABLES

Using variables1. Choose a name for your variable2. Declare your variable3. Initialize your variable

Page 48: Lecture 1 introduction to_computersb(2)

VARIABLES

Using variables1. Choose a name for your variable

The identifier chosen must be valid (cf. rules) The identifier should be meaningful

ex: numOfSales is more meaningful than ‘n’ or ‘number’

Page 49: Lecture 1 introduction to_computersb(2)

VARIABLES

Using variables2. Declare your variable

That is, let java know that you are going to use this variable, by declaring its name and type

Use a declaration statement within a block <Type> <identifier>; e.g.:

int numOfSales;

Page 50: Lecture 1 introduction to_computersb(2)

VARIABLES

Using variables3. Initialize your variable

Use an assignment statement. (you assign a value to a variable)

<identifier> = <literal>; e.g.:

numOfSales = 0;

Page 51: Lecture 1 introduction to_computersb(2)

VARIABLES What is a literal?

the source code representation of a fixed value boolean

‘true’ or ‘false’ e.g.:

boolean hasPaidMembership; hasPaidMembership = false;

Page 52: Lecture 1 introduction to_computersb(2)

VARIABLES What is a literal?

byte, short, int Usual decimal notation, i.e. an optional minus sign,

followed by a sequence of digits from 0 to 9 e.g.:

int numOfSales ; numOfSales = 4;

Or using octal notation (digits from 0-7, use prefix 0) e.g.:

int octalNum; octalNum = 011; //9 in decimal

Or using hexadecimal notation (digits from 0-9 and A-F, use prefix 0x)

e.g.: int MACAddress; MACAddress = 0x10EA; //4330 in decimal

Page 53: Lecture 1 introduction to_computersb(2)

VARIABLES

What is a literal? long

same as int, but followed by a ‘L’ or a ‘l’ e.g.: in decimal

long numOfWalMartSales; numOfWalMartSales = 0L;

e.g. in decimal: long ycoordinate; ycoordinate = -3000000000L;

e.g. in hexadecimal: long longHexadecimalValue; longHexadecimalValue = -0x13A26E612L;// 5270595090 in decimal

Page 54: Lecture 1 introduction to_computersb(2)

VARIABLES

What is a literal? double

Using the usual decimal notation: optional minus or plus sign followed by a sequence of digits , and an optional decimal point

Optionally followed by a ‘d’ or ‘D’ e.g.:

double surfaceArea; surfaceArea = +123.54;

Or using the scientific notation: product of a number and a power of 10 , the number is followed by ‘e’ or ‘E’ and the power of ten

e.g. declaring and initializing a variable to -6.1×10−9 double doubleValue; doubleValue = -6.1e-9;

Page 55: Lecture 1 introduction to_computersb(2)

VARIABLES

What is a literal? float

Same as double, but followed by a ‘f’ or a ‘F’ e.g.:

float surfaceArea; surfaceArea = +123.54f;

e.g. in scientific notation float floatValue; floatValue = -6.1e-9F;

Page 56: Lecture 1 introduction to_computersb(2)

VARIABLES

What is a literal? char

Any Unicode character, between simple quotes e.g.:

char middleInitial; middleInitial = 'F';

If your editor does not allow it, you can insert a character’s unicode code:

e.g. ñ char specialChar; specialChar = '\u00F1';

Page 57: Lecture 1 introduction to_computersb(2)

VARIABLES

What is a literal? String

Any sequence of Unicode characters, between double quotes

e.g.: String firstName; firstName = "Nelly";

If your editor does not allow it, you can insert a character’s unicode code:

e.g. String fullName; fullName = "Mr Fernando Ca\u00F1ero ";

Page 58: Lecture 1 introduction to_computersb(2)

VARIABLES

You are ready to use local variables! Choose a name for your variable Declare your variable Initialize your variable

Page 59: Lecture 1 introduction to_computersb(2)

VARIABLES

Shortcuts Declare and initialize a variable in a single

statement <type> <identifier> = <literal>; e.g.:

char middleInitial = 'F'; float floatValue = -6.1e-9F; int numOfSales = 3; String sentence = “My name is";

Page 60: Lecture 1 introduction to_computersb(2)

VARIABLES

Shortcuts Declare multiple variables of the same

type in a single statement <type> <identifier1>, <identifier2>, …; e.g.:

char middleInitial, gender; float floatValue, surfaceArea, ratio; int numOfSales, age; String firstName, middleName, lastName;

Page 61: Lecture 1 introduction to_computersb(2)

VARIABLES

Shortcuts Declare and initialize multiple variables in

a single statement <type> <identifier1> = <literal1>,

<identifier2> = <literal2>, <literal3>, …; e.g.:

char middleInitial ='F', gender; float floatValue, surfaceArea = 2.3, ratio; int numOfSales = 9, age = 6; String firstName = "Nelly", middleName, lastName;

Page 62: Lecture 1 introduction to_computersb(2)

VARIABLES

Scope Where do I declare local variables?

in any block, within a method In what parts of the source code can I access a

local variable (i.e., what is the scope of a local variable)?

the rest of the block in which the declaration appears

Page 63: Lecture 1 introduction to_computersb(2)

VARIABLES

Variable output The output statement described in the previous

lecture also works with variables of primitive data types and with String variables:

omit the double quotes and specify the name of the variable between the braces

Page 64: Lecture 1 introduction to_computersb(2)

VARIABLES

Variable output You can mix constant strings and variables by

using ‘+’ ‘+’ is used for concatenating a string and the

value of your variable, e.g.:

Produces: