Title: G51PR1
1G51PR1
- Introduction to Programming I
- 2000-2001
- University of Nottingham
- Unit 2 Elementary Programming
2Overview
- Writing Java programs
- Simple program
- Comments
- Printing to the screen
- Constants and Variables
- Identifiers
- Syntax Semantics
- Errors
- Primitive Types
- Literals
- Program Layout
- Operators
- Comparison
- Logical
- Incremental
- Assignment
- Program Input
- Conversions
3A simple program
Filename HelloWorld.java
// Program written by azt / September 1998
/ import java.lang. / Example class
HelloWorld / public class HelloWorld
public static void main(String argv )
System.out.println("Hello World!")
comments
method body
class body
4Notes on the HelloWorld program
- Java is case-sensitive
- The import statement allows us to use the
println() function of the out object (of class
PrintStream) a member of the System class of the
java.lang package. - public class HelloWorld is the declaration of a
new class called HelloWorld. - main() is the entry point for the program, that
is the point at which execution starts. - The body of the class and main function is
contained within the and symbols. - Every statement which is an instruction to the
computer must be ended with a semi-colon. main()
and and are part of the layout of the
program not instructions as such. - The println() function allows us to print a
string "Hello World!!". - White space layout (tabs, newlines, spaces etc)
is not enforced but should be used sensibly! More
later on program layout.
5Comments
Three ways of commenting 1. Rest of the line
comment // rest of this line is a
comment 2. Multiple line comments / This
is a multiple line comment like in C or
C / 3. JavaDoc Comments /
This comment will be included in
documentation generated with 'javadoc'.
/
6Program Output
- // to print more complex items
- System.out.println("Hello " "World!!!")
- // or you could write
- System.out.print("Hello ")
- System.out.println("World!!!")
- // you could write
- System.out.println("Colin Higgins")
- System.out.println("School of Computer
Science and IT") - System.out.println("University of
Nottingham") - // or you could write
- System.out.println("Colin Higgins\nSchool
of Computer Science and - IT\nUniversity of Nottingham")
7Constants and variables
- We wish to have identifiers to represent
- 1.Constants whose values is required in the
program and - 2.Variables which will be used for storing
intermediate results. - For each identifier we use, we must tell the
computer the type we wish to use it for. The
general syntax is - typename identifier
- typename identifier1, identifier2
- typename identifier expression
- typename identifier1 expression1,
identifier2 expression2
8Examples
- int i
- float scale
- boolean correct, valid
- double diamond, YourMoney
- char Signature X
- long StartValue 123456789L
- byte MyByte 0x12, YourByte 0x4F
- String name "Colin", uid "cah"
- In many circumstances constants are allowed
- final float PI 3.14159f
- float diameter 4.0f
- float circumference diameter PI
9A Simple Example (with 2 errors)
import java.io. class Add2Numbers float
PI3.14F public static void main(String
argv ) double a,b,c // declare
variables a 1.75 // assign values b 3.46
c a b // add them together char c
Y System.out.println(sum
c) System.out.println(Pi PI ) //
end class Add2Numbers
10Identifiers
- Variables and constants, need to be given names
to allow us to access them. - An identifier is a sequence of allowable
characters that names something within the
program. - The identifiers you choose must satisfy various
rules and recommendations. - The exact rules are somewhat complex in Java
because of Unicode. - Here is a simple guide
- They must start with a letter. This may be
followed by any number of letters, - underscores and digits. Upper and lower case
letters are distinct, that is - LoopVariable is different from loopVariable. You
should use meaningful variables. - They should not clash with reserved or other
special words eg float, boolean etc.
11Identifiers Example
- To sum up, identifiers in java can contain any
combination of upper-case, lowercase, numbers and
_', but must not begin with a number.
Valid
Invalid
stack, Stack, STACK_SIZE wav2snd, _snd, snd
3d, 5, snd, sndwav
12Reserved Identifiers
- Some identifiers,have specific meanings in Java
and cannot be used differently.
abstract boolean break byte case catch char class
const continue
goto if implements import instanceof int interface
long native new null
package private protected public return short stat
ic super switch
synchronized this throw throws transient true try
void volatile while
default do double else extends false final finally
float for
13Syntax and Semantics
- The syntax of a language defines how you can put
symbols, reserved words, and identifiers together
to make a valid program - The semantics of a language construct is the
meaning of the construct it defines its role in
a program - A syntactically correct program does not mean it
is logically (semantically) correct - A program will always do what we tell it to do,
not what we meant to tell it to do
14Errors
?
- 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)
15Primitive Types
- The basic Java types are given below along with
their use, number of bytes required and their
ranges
63
63
16Literals
- A literal is an explicit data value used in a
program - Integer literals
- 25 69 -4288
- Floating point literals
- 3.14159 42.075 -0.5
- Char literal a
- String literals
- Hello World
- Boolean literals
- true false
- null
17Literals
- Integers 42, 0, -22, 69, 345678
- Octals 0177, 00, 0777, -023
- Hexadecimals 0x0, -0x1, 0x34af, 0XA9B3
- Longs 0L, 0l, 12345678L, 0xab12345L,
-87654321L - Floats 123.456, -654.321, 0.0, 0.98
- 1.23f, 45.678F, 2.567d, 7.374D
- 6.564e23, 1.23E-12, 4.35e3D,
-3.456E34f - Boolean
- true, false
- Characters
- a, b, A, 3, ,
- \b, \n, \r, \\, \t, \
- \123, \234, \012
- Strings "This is a string literal", "Hello
World!!!\n", "left\tcentre\tright\t" - Null null
18Program layout
- Remember humans are good at pattern recognition
so use this to minimise errors! - Layout your program carefully.
- Leave plenty of white space.
- Indent as appropriate.
- Use one of the recommended conventions.
- Stick to the same convention.
- As programs become bigger, layout becomes more
and more important. - More later!
19Operators
- Arithmetic
- ()
- /
- -
- Example Program 1 Convert Fahrenheit
temperature to Celsius. - float celsius
- // input is a little tricky, so set a value
here... - float fahrenheit 57f
- celsius (fahrenheit 32) 5 / 9
- System.out.println("Celsius is " celsius)
20Example Program 2
- I have a certain number of bicycle spokes
- I need 44 to make one wheel how many wheels can
I make? - How many spokes will I have left over?
- static final int spokesPerWheel 44
- int wheels, leftOver
- int spokes 839
- wheels spokes / spokesPerWheel
- leftOver spokes spokesPerWheel
- System.out.println("Number of wheels is "
wheels) - Etc.
21Example Program 3
- We know the number of football matches won
drawn and lost for a given team how many points
do they have? (three for a win, one for a draw) - int won 7
- int drawn 4
- int lost 37
- int points
- points won 3 drawn
- System.out...
22Comparison operators
- gt // greater than
- lt // less than
- gt // greater than or equal to
- lt // less than or equal to
- // equals watch for the double ""!!!
- ! // not equals
- These can be used between any relevant types of
object. - The result delivered is a boolean true or false.
- Note testing for equality "" between floats or
doubles is rarely, if ever, sensible due to the
possibility of rounding errors. - Examples
- fahrenheit gt 32
- spokes gt 2 spokesPerWheel
23Logical operators
- // conditional and
- // conditional or
- ! // logical complement (not)
- // boolean and
- // boolean or
- // boolean exclusive or
- We need general logical operators to combine the
results of comparisons (or of booleans). - Beware, the last three or these operators ( )
have other meanings in different circumstances! - Examples number gt 0 number lt 10
- number gt 0 number lt 10
- number lt 0 number gt 10
- ! ( number gt 0 number lt 10)
- Can I construct at least 2 wheels with less than
10 spokes left over? - spokes 2 spokesPerWheel spokes
spokesPerWheel lt 10
24Incremental operators
- These (like most of the operators and fundamental
language control constructs) come from C/C - i // increment, deliver new value
- i // increment, deliver old value
- --i // decrement, deliver new value
- i-- // decrement, deliver new value
- "increment" means increase by a suitable value,
usually 1. - Compare
- i 0 System.out.println(i)
- which prints out value 0, with
- i 0 System.out.println(i)
- which prints out value 1. In both
cases i has value 1 afterwards.
25Incremental Operators
- Example equivalent
- j p i j p i i i 1
- j p i i i 1 j p i
- j p (i) i i 1 j p i
- You will often see the free standing increment
- i // increment i, sometimes you will see I
- to add 1 to i rather than i i 1
26Assignment
- Assignment is also an operator.
- There are many types of assignments Java like
C/C is rich in operators. - int i i 3
- float f 0.3456
- char ch A
- assignment can be combined with other operators
- i 4 // plus-and-becomes ie i i 4
- i - j // minus-and-becomes ie i i j
- f 4.2 // multiply-and-becomes ie f f
4.2 - a b // logical -and-becomes ie a a
b - i 1 // normally you would see i
27Assignment
- The assignment operator has a value itself, as
well as doing the assignment.Thus - i j k 0
- works like
- i ( j ( k 0 ) )
- since is right to left associative.
- Note that in initialising declarations, you must
still write in full - int i 0, j 0, k 0
- Example 1
- How many bicycle wheels can I make, and how many
spokes will I have used? - wheels spokes / spokesPerWheel
- spokesUsed wheels spokesPerWheel
28Operator precedence
- It is necessary to carefully define the meaning
of such expressions as - a b c
- in this case to give
- a ( b c )
- All operators have a priority, higher ones are
evaluated first. - Operators with equal priority are normally
evaluated left-to-right - (they are left (L) associative), so that
- a b c
- is evaluated as
- ( a b ) c
29Operator precedence
- Operator Operand Type(s) Assoc.
Operation Performed - arithmetic R pre-or-post increment
(unary) - -- arithmetic R pre-or-post decrement
(unary) - , - arithmetic R unary
plus, unary minus - integral R bitwise
complement (unary) - ! Boolean R logical
complement (unary) - (type) any R cast
- , /, arithmetic L multiplication,
division, remainder - , - arithmetic L addition, subtraction
- string L string concatenation
- ltlt integral L left shift
- gtgt integral L right shift with sign extension
- gtgtgt integral L right shift with zero extension
- lt, lt arithmetic L less than, less than or
equal - gt, gt arithmetic L greater than, greater than
or equal - Instanceof object, type L type comparison
30Operator Precedence
- Operator Operand Type(s) Assoc.
Operation Performed - primitive L equal
(have identical values) - ! primitive L
not equal (have different values) - object L
equal (refer to same object) - ! object L not
equal (refer to different objects) - integral L bitwise
AND - boolean L boolean
AND - integral L
bitwise XOR - boolean L
boolean XOR - integral
L bitwise OR - boolean L
boolean OR - boolean L
conditional AND - boolean L
conditional OR - ? boolean, any, any R
conditional (ternary) operator - variable, any R
assignment - , /, , , -, ltlt,gtgt, gtgtgt, , ,
- variable, any R assignment with operation
31Program input
- There are many different ways of inputting
strings, chars, ints, floats, etc - For now just follow the code shown below (and
import java.io.). - To read a long from the keyboard use the
following code - long Number 0
- DataInputStream dis new DataInputStream(System.
in) - try
- String userInput new String(dis.readLine())
- Number (java.lang.Long.valueOf(userInput)).lo
ngValue() -
- catch(IOException e)
- System.out.println("Exception while reading
input") -
32Example
- Here is a full example of reading and writing a
value - public class hal
- public static void main(String argv)
- int i 0
- // Prompt and read
- System.out.print("Type a number ") // Note,
not println - System.out.flush() // causes output
- DataInputStream dis new DataInputStream(Syst
em.in) - try
- String userInput new String(dis.readLine(
)) - i (java.lang.Int.valueOf(userInput)).intV
alue() -
- catch(IOException e)
- System.out.println("Exception while
reading input") - System.out.println("Value was " i)
-
33Conversions
- Other conversions are possible
- boolean b java.lang.Boolean.valueOf(String
s).booleanValue - short sh java.lang.Short.valueOf(String
s).shortValue - and so on with
- Character char
- Byte byte
- Integer int
- Long long
- Float float
- Double double
- Note for later Character, Byte etc are immutable
class wrappers around each of the primitive Java
data types
34Summary
- Writing Java programs
- Simple program
- Comments
- Printing to the screen
- Constants and Variables
- Identifiers
- Syntax Semantics
- Errors
- Primitive Types
- Literals
- Program Layout
- Operators
- Comparison
- Logical
- Incremental
- Assignment
- Program Input
- Conversions