Title: Lesson B - Basic Java Elements
1Lesson B - Basic Java Elements
2Hello World Program, Again
// My First Program!! public class HelloWorld
public static void main(String args)
System.out.println(Hello World!)
3Identifiers Syntax
- 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
4Identifiers 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
5Naming 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!
6White 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
7Valid, but bad Indentation
public class HelloWorld
public static void main(String
args)
System.out.println(Hello World!)
8Comments
- 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 /
9Lesson 2 - Basic Java Elements
- Unit B2 - Variables and Data Types
10Variables
- 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
11VariableExample Program
public class VariableExample public static
void main(String args) int x x 3
System.out.println(x) x 4
System.out.println(x)
12VariableExample 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
13VariableExample 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)
3
x
14VariableExample 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)
3
x
15VariableExample 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)
4
x
16VariableExample 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)
4
x
17Primitive 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
18Integers
- 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
19Floating Point
- There are two floating point types
Type Bits Range (decimal digits) Precision (decimal digits)
float 32 38 7
double 64 308 15
20Characters
- 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)
21Boolean
- 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
22Variable 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
23Variable Declaration Example
public class DeclarationExample public static
void main (String args) int weeks 14
long numberOfStudents 120 double
averageFinalGrade 78.6 System.out.println(w
eeks) System.out.println(numberOfStudents)
System.out.println(averageFinalGrade)
24More Variable Examples
double pi, conversionRate, temprature long
salary boolean isOn char c pi 3.14159 isOn
false c A salary 34000 isOn true
25Constants
- 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
26Lesson 2 - Basic Java Elements
27Assignment 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
28Arithmetic 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
29Pounds to Kg conversion
public 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)
30Pounds to Kg conversion 2
public class PoundsToKg2 public static void
main(String args) final double
KILOS_IN_POUND 0.455 System.out.println(200
.0 KILOS_IN_POUND)
31Integer 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
32Complex 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)
33Operator 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.
34Operator 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
35Conversions
- 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
36Conversion 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
37Lesson 2 - Basic Java Elements
- Unit B4 - Objects and Method Invocation
38Reference 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
myName
t
today
Memory
39Creating 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()
40Creating 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
41Creating 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
42Creating 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
43Strings
- 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
44Method invocations
- You may invoke methods on an object. Methods may
receive parameters. - Methods may also return values.
Turtle leonardo new Turtle() leoardo.moveForwar
d(100) String lennon John Lennon int len
lennon.length() char initial lennon.charAt(5)
45APIs
- 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.
46Javadoc example
47Javadoc example (2)
48Class 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)
49RandomNumbers.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(A
nother one num)
50Lesson 2 - Basic Java Elements
- Unit B5 - Input and Output
51Types 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
52The 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()
53InputRequestor 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.
54The 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()
55The Output Window
56The showMessage() Pop-up Window
57Circle 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)
58Lesson 2 - Basic Java Elements
- Unit B6 - Introduction to Applets and Graphics
59The Web
60My First HTML Example
ltH3gtMy First HTML Filelt/H3gt ltpgt Hello
World!!! ltpgt Here is a link to lta
hrefhttp//www.cnn.comgtCNNlt/agt!
61My First Web Page
62Running 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
63A Web Page with an Embedded Applet
64Writing 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
65Smiley.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)
66Smiley.HTML
ltH3gtMy Smiley Appletlt/H3gt ltapplet
codeSmiley.class" width400 height400gt lt/applet
gt ltpgt Above this text you should see Smiley!!
- The Smiley.class file should be placed in the
same directory with Smiley.HTML
67Smiley
68Graphics Coordinates
10
150
20
45
page.drawLine (10, 20, 150, 45)
69Drawing an Oval
175
20
page.drawOval (175, 20, 50, 80)