Vous êtes sur la page 1sur 69

Slide 1 of 69.

Lecture B
Basic Java Elements
Program Elements
Slide 2 of 69. Lecture B
Hello World Program, Again
// My First Program!!
public class HelloWorld {
public static void main(String[] args){
System.out.println(Hello World!);
}
}
Slide 3 of 69. Lecture B
Identifiers are the words a programmer uses in a program
Identifier syntactic rules:
Can be made up of any length of
letters
digits
underscore character (_)
dollar sign ($)
Cannot begin with a digit
Java is case sensitive
User and user are completely different identifiers

Slide 4 of 69. Lecture B
Identifiers: Semantics
Identifiers names can come from the following sources
Fixed in Java as reserved words
public, class, static, void, method,
Chosen by the programmer to denote something
HelloWorld, main, args
Chosen by a programmer whose code we use:
String, System, out, println

Slide 5 of 69. Lecture B
Naming style
The correctness of the program is not affected by the
names used
public class X7_65Tx { }
Names play a central role in the readability of the program
They are part of its documentation
They should thus be chosen carefully
BankAccount, size, numberOfElements
Follow conventions in choosing names!

Slide 6 of 69. Lecture B
White Space
Spaces, blank lines, and tabs are collectively called white
space
White space is used to separate words and symbols in a
program
Extra white space is ignored
A valid Java program can be formatted many different
ways
Programs should be formatted to enhance readability,
using consistent indentation

Slide 7 of 69. Lecture B
Valid, but bad Indentation
public class
HelloWorld { public static void

main(String[]
args) {
System.out.println(Hello World!)
;}}

Slide 8 of 69. Lecture B
Comments
Comments are ignored and are treated as white space
They should be written to enhance readability
Explain what a piece of code does (its interface)
Explain any special tricks, limitations,
Java has three comment formats:
// comment to end of line
/* comment until
closing */
/** API specification comment */




Slide 9 of 69. Lecture B
Basic Java Elements
- Variables and Data Types
Slide 10 of 69. Lecture B
Variables
A variable is a location in memory that can hold values of
a certain data type
Each variable must be declared before it is used
The declaration allocates a location in memory to hold
values of this type
Variable types can be
primitive
reference to an object

Slide 11 of 69. Lecture B
VariableExample Program
public class VariableExample {
public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}

Slide 12 of 69. Lecture B
VariableExample Program (2)
public class VariableExample {
public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}

x
Slide 13 of 69. Lecture B
VariableExample Program (3)
public class VariableExample {
public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}

x
3
Slide 14 of 69. Lecture B
VariableExample Program (4)
public class VariableExample {
public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}

x
3
Slide 15 of 69. Lecture B
VariableExample Program (5)
public class VariableExample {
public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}

x
4
Slide 16 of 69. Lecture B
VariableExample Program (6)
public class VariableExample {
public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}

x
4
Slide 17 of 69. Lecture B
Primitive Data Types
A data type is defined by a set of values and the
operators you can perform on them
The Java language has several predefined types, called
primitive data types
The following reserved words represent the eight different
primitive data types:
byte, short, int, long, float, double, boolean,
char

Slide 18 of 69. Lecture B
Integers
There are four integer data types. They differ by the
amount of memory used to store them

Type Bits Value Range
byte 8 -127 128

short 16 -32768 32767

int

32

about 9 decimal digits
long 65 about 18 decimal digits

Slide 19 of 69. Lecture B
Floating Point
There are two floating point types
Type Bits Range
(decimal digits)
Precision
(decimal digits)
float 32 38 7
double 64 308

15
Slide 20 of 69. Lecture B
Characters
A char value stores a single character from the Unicode
character set
A character set is an ordered list of characters
A, B, C, , a, b, ,0, 1, , $,
The Unicode character set uses 16 bits per character,
allowing for 65,536 unique characters
It is an international character set, containing symbols and
characters from many world languages
The ASCII character set is a subset of Unicode
ASCII is the current standard (outside of Java)

Slide 21 of 69. Lecture B
Boolean
A boolean value represents a true/false condition.
It can also be used to represent any two states, such as a
light bulb being on or off
The reserved words true and false are the only
valid values for a boolean type

Slide 22 of 69. Lecture B
Variable Declarations
The syntax of a variable declaration is
data-type variable-name;
For example

Multiple variables can be declared on the same line

Variables can be initialized (given an initial value) in the
declaration



int total;
long total, count, sum;
int total = 0, count = 20;
double unitPrice = 57.25;
Slide 23 of 69. Lecture B
Variable Declaration Example
public class DeclarationExample {
public static void main (String[] args) {
int weeks = 14;
long numberOfStudents = 120;
double averageFinalGrade = 78.6;
System.out.println(weeks);
System.out.println(numberOfStudents);
System.out.println(averageFinalGrade);
}
}

Slide 24 of 69. Lecture B
More Variable Examples
double pi, conversionRate, temprature;
long salary;
boolean isOn;
char c;

pi = 3.14159;
isOn = false;
c = A;
salary = 34000;
isOn = true;

Slide 25 of 69. Lecture B
Constants
We may declare that a variable is a constant and its value
may never change.



Advantages:
readability
efficiency
error detection

final double PI = 3.14159;
final int CHINA_OLYMPICS_YEAR = 2008;
Slide 26 of 69. Lecture B
Basic Java Elements
Expressions
Slide 27 of 69. Lecture B
Assignment Statements
An assignment statement takes the following form
variable-name = expression;
The expression is first evaluated
Then, the result is stored in the variable, overwriting the
value currently stored in the variable

Slide 28 of 69. Lecture B
Arithmetic Operators
An operator is a mapping that maps one or more values
to a single value:
Binary Operators:
a + b adds a and b
a - b subtracts b from a
a * b multiplies a and b
a / b divides a by b
a % b the reminder of divining a by b
Unary Operator:
-a The negation of a

Slide 29 of 69. Lecture B
Pounds to Kg conversion
class PoundsToKg {
public static void main(String[] args){
double weightInPounds = 200.0;
final double KILOS_IN_POUND = 0.455;
double weightInKg;

weightInKg = weightInPounds * KILOS_IN_POUND ;
System.out.println(weightInKg);
}
}
Slide 30 of 69. Lecture B
Pounds to Kg conversion 2
class PoundsToKg2 {
public static void main(String[] args){
final double KILOS_IN_POUND = 0.455;
System.out.println(200.0 * KILOS_IN_POUND);
}
}
Slide 31 of 69. Lecture B
Integer Division
When division is performed on integers (byte, short,
int, long), the result is truncated to an integer.

int j = 5;
double x = 5.0, y;
System.out.println(j / 2); // 2
System.out.println(x / 2.0); // 2.5
System.out.println(5 / 2); // 2
y = j / 2 ; // 2
Slide 32 of 69. Lecture B
Complex Expressions
Expressions can combine many operators and operands
Examples:
x
-34
weight * 2.73
2 * PI * r
a - (7 b)
1 + 2 + 3 + 4
(x + y) * (2 - z + (5 - q)) * -(1-x)
Slide 33 of 69. Lecture B
Operator Precedence
Multiplication, division, and remainder (%) have a higher
precedence than addition and subtraction.
Operators with same precedence evaluate from left to
right.
Parenthesis can be used to force order of evaluation.

Slide 34 of 69. Lecture B
Operator Precedence Examples
Expression Result
10 - 7 - 1 2
10 - (7 - 1) 4
1 + 2 * 3 7
(1 + 2) * 3 9
1 - 2 * 3 + 4 * 5 15
Slide 35 of 69. Lecture B
Conversions
Data types can be mixed in an expression
When the expression is evaluated one type is converted
to another
Data is converted to a wider type in three cases
assignment conversion
arithmetic promotion
casting
Can be converted to a narrower type only by casting
List of types from narrowest to widest:
Narrow Wide
byte short int long float double
Slide 36 of 69. Lecture B
Conversion Examples
double f, x;
int j;
f = 5;
f = 5.0 / 2;
f = x * j;
f = 5 / 2;
f = (float) j / 5;
j = (int) f;
j = (int) 5.0 / 2.0;
Slide 37 of 69. Lecture B
Basic Java Elements
Objects and Method Invocation
Slide 38 of 69. Lecture B
Reference Types
Variables can be declared to be of an object type. In this
case they hold a reference to an object of this type (class).
Turtle t;
String myName;
Date today;
Memory
t today
myName
Slide 39 of 69. Lecture B
Creating Objects
Objects are created by invoking a constructor of the class.
Constructors may accept parameters.

Date today;
today = new Date(12345);// mSec since 1.1.1970
Turtle t = new Turtle();
Slide 40 of 69. Lecture B
Creating Objects (2)
Objects are created by invoking a constructor of the class.
Constructors may accept parameters.

Date today;
today = new Date(12345);// mSec since 1.1.1970
Turtle t = new Turtle();
today
Slide 41 of 69. Lecture B
Creating Objects (3)
Objects are created by invoking a constructor of the class.
Constructors may accept parameters.

Date today;
today = new Date(12345);// mSec since 1.1.1970
Turtle t = new Turtle();
today
12345
Slide 42 of 69. Lecture B
Creating Objects (4)
Objects are created by invoking a constructor of the class.
Constructors may accept parameters.

Date today;
today = new Date(12345);// mSec since 1.1.1970
Turtle t = new Turtle();
t today
12345
Slide 43 of 69. Lecture B
Strings
Strings are objects that are treated by the compiler in special
ways:
Can be created directly using xxxx
Can be concatenated using +

String myName = John Jones;
String hello;
hello = Hello World;
hello = hello + !!!!;
int year = 2008;
String s = See you in China in + year;
Slide 44 of 69. Lecture B
Method invocations
You may invoke methods on an object. Methods may
receive parameters.
Methods may also return values.
Turtle leonardo = new Turtle();
leoardo.moveForward(100);
String lennon = John Lennon;
int len = lennon.length();
char initial = lennon.charAt(5);
Slide 45 of 69. Lecture B
APIs
To use an object you only need to know its application
programmer interface (API).
The API of an object class includes a description of:
all available constructors and methods and what they do
the parameters they take and the values that they return
The API is usually given in a special format called
javadoc.

Slide 46 of 69. Lecture B
Javadoc example
Slide 47 of 69. Lecture B
Javadoc example (2)
Slide 48 of 69. Lecture B
Class Libraries
A class library is a collection of classes that we can use
when developing programs
There is a standard class library that comes with every
Java environment.
Class Libraries are organized into packages
java.net, java.lang, java.io, ...
To use classes from a package you must either
Import the package


Or, use a fully qualified class name

import java.io.*;
File f = new File(John);
java.io.File f = new java.io.File (John);
Slide 49 of 69. Lecture B
RandomNumbers.java
import java.util.Random;
public class RandomNumbers {
public static void main (String[] args){
Random generator = new Random();
int num = generator.nextInt();
System.out.println ("A random int: " + num);
num = generator.nextInt();
System.out.print(Another one: + num);
}
}
Slide 50 of 69. Lecture B
Basic Java Elements
Input and Output
Slide 51 of 69. Lecture B
Types of Input and Output (I/O)
Terminal-based I/O
System.out.println()
System.in.xxxxx()
Graphic User Interface
Windows, Buttons, Mouse,
Stream based I/O
Files, Web, Communication, Terminal-based I/O
In this course we also provide our own classes:
InputRequestor, OutputWindow

Slide 52 of 69. Lecture B
The InputRequestor Class
To use the input requestor, you must first create the
object:
InputRequestor inp = new InputRequestor();

Then, you may use it to read primitive data types:
int i = inp.requestInt();
int i = inp.requestInt(Enter age:);
float f = inp.requestFloat();
Slide 53 of 69. Lecture B
InputRequestor Behaviour
A window will pop up every time you use the
requestXXX() method:





The window will disappear only after you have typed a
legal input. The method returns this input.

Slide 54 of 69. Lecture B
The OutputWindow Class
Just as System.out enables you to display output in the
MS-DOS window, you may display output in your own
window.
Create an OutputWindow object:


Useful methods in the output window:
println() - just as regular println().
clear() - clears the output window.
showMessage() - pop up a message on the desktop.

OutputWindow outwin = new OutputWindow();
Slide 55 of 69. Lecture B
The Output Window
Slide 56 of 69. Lecture B
The showMessage() Pop-up Window
Slide 57 of 69. Lecture B
Circle Area and Circumference
public class CircleCalc {
public static void main(String[] args){
final double PI = 3.14159;
InputRequestor in = new InputRequestor();
OutputWindow out = new OutputWindow();
double r = in.requestDouble("Radius: ");
out.println("Radius = " + r);
out.println("Area = " + PI * PI * r);
out.println("Circumference = " + 2 * PI * r);
}
}
Slide 58 of 69. Lecture B
Lesson 2 - Basic Java Elements
Unit B6 - Introduction to Applets and Graphics
Slide 59 of 69. Lecture B
The Web
Slide 60 of 69. Lecture B
My First HTML Example
<H3>My First HTML File</H3>

<p>
Hello World!!!
<p>
Here is a link to
<a href=http://www.cnn.com>CNN</a>!
Slide 61 of 69. Lecture B
My First Web Page
Slide 62 of 69. Lecture B
Running programs in a web page
Java was invented so that running programs can be
embedded in web-pages
Such Java programs are called Applets
This had to solve some problems
Platform independence
browsers have a built-in Java byte-code interpreter
Security
the program runs in the browser in a sandbox

Slide 63 of 69. Lecture B
A Web Page with an Embedded Applet
Slide 64 of 69. Lecture B
Writing Applets
An Applet does not have a main method.
Instead, it has a set of methods that control the interaction
with the user.
An Applet inherits this interface from the
java.applet.Applet class
The paint method has to paint the screen
It receives a Graphics object, and uses it to paint
The Graphics class has various drawXXX() methods

Slide 65 of 69. Lecture B
Smiley.java
import java.applet.Applet;
import java.awt.*;
public class Smiley extends Applet{
public void paint (Graphics page){
page.setColor(Color.yellow);
page.fillOval(50,50,300,300);
page.setColor(Color.black);
page.fillOval(125,125,50,50);
page.fillOval(225,125,50,50);
page.drawLine(150,275,250,275);
}
}
Slide 66 of 69. Lecture B
Smiley.HTML
The Smiley.class file should be placed in the same
directory with Smiley.HTML
<H3>My Smiley Applet</H3>
<applet code=Smiley.class" width=400 height=400>
</applet>
<p>
Above this text you should see Smiley!!

Slide 67 of 69. Lecture B
Smiley
Slide 68 of 69. Lecture B
Graphics Coordinates
X
Y
10
20
150
45
page.drawLine (10, 20, 150, 45);
Slide 69 of 69. Lecture B
Drawing an Oval
X
Y
175
20
50
80
page.drawOval (175, 20, 50, 80);

Vous aimerez peut-être aussi