COP2800– JAVA PROGRAMMING Dr Delessy-Gassant
Nov 28, 2014
COP2800– JAVA PROGRAMMINGDr Delessy-Gassant
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
THE COMPONENTS OF A COMPUTER
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
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
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
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.
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.
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
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
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
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
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/
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
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
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
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
INTRODUCTION TO COMPUTERS
Other characteristics of Java: Popular Object-oriented Simple Portable Robust/secure
INTRODUCTION TO COMPUTERS
In the labs, we use a powerful tool: Netbeans Editor Compiler Interpreter And more…
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?
…
INTRODUCTION TO JAVA APPLICATIONS
(One of )the simplest Java program:
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
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)
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, …
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
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
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
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
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’, …)
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
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
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 “”
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
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)
=
INTRODUCTION TO JAVA APPLICATIONS
Final remarks Code formatting does not matter
White spaces (space, tabulations, blank lines..) can be used interchangeably
=
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)
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
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
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,…
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
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
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
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
VARIABLES
Ex: number of sales per day in all Walmart stores?
Number of sales per day in your local computer shop?
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
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
VARIABLES
Using variables1. Choose a name for your variable2. Declare your variable3. Initialize your variable
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’
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;
VARIABLES
Using variables3. Initialize your variable
Use an assignment statement. (you assign a value to a variable)
<identifier> = <literal>; e.g.:
numOfSales = 0;
VARIABLES What is a literal?
the source code representation of a fixed value boolean
‘true’ or ‘false’ e.g.:
boolean hasPaidMembership; hasPaidMembership = false;
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
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
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;
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;
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';
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 ";
VARIABLES
You are ready to use local variables! Choose a name for your variable Declare your variable Initialize your variable
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";
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;
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;
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
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
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: