Transcript lecture07
Basic Java Syntax
INE2720
Web Application Software Development
Essential Materials
Outline
Primitive types
Arithmetic, logical and relational operators
Conditional expressions and loops
Reference types
Building arrays
Using wrappers to convert primitive data
types to objects
Handling exceptions
INE2720 – Web Application Software Development
2
All copyrights reserved by C.C. Cheung 2003.
Primitive Types
Java has two fundamentalk inds of data
types: P rimitive and Refe
r ence
– Primitive are those types not “objects”
– Boo
l ean
: true / fa
l se
– char: 1 6-bit unsigned integer representing a
Unicode character.
– byte
: 8-bit, signed, two’s comp
l ement integer.
– short: 1 6-bit, signed, two’s comp
l ement integer.
– int: 32-bit, signed, two’s comp
l ement integer.
– long
: 64
-bit, signed, two’s comp
l ement.
– fl oat: 32-bit lf oating-point, doub
l e
: 64
-bit fp.
INE2720 – Web Application Software Development
3
All copyrights reserved by C.C. Cheung 2003.
Primitive-type conversion
Type2 type2Var = (Type2) type1Var;
int i = 3;
byte b = (byte) i;
// cast i to a byte
long x = 123456L;
short s = (short) x;
// cast x to a short, lossy
double d = 3.1416;
float f = (float) d;
// cast from 64 to 32 bits
short s = (short) f;
// cast a float to a short
int i = s;
// upward conversion, no cast is needed
INE2720 – Web Application Software Development
4
All copyrights reserved by C.C. Cheung 2003.
Operators
Operators
Meaning
Example
+, -
Add and subtract
x = y + 5;
*, /, %
Multiply, divide, remainder
z = x / y;
++, --
Prefix/postfix increment and decrement
x = i++; y = --j;
<<, >>, >>> Signed and unsigned shifts
y = x << 2;
~
Bitwise complement
x = ~127; // -128
&, |, ^
Bitwise AND, OR, XOR
x = 127 & 2;
==, !=
Equality, inequality
x = (1 == 1);
<, <=, >, >=
Numeric less than, less than or equal to, …
x = (2 > 3);
&&, ||
Logical AND, OR
(2 > 3) && (3 ==3)
!
Logical negation
!(2 > 3)
INE2720 – Web Application Software Development
5
All copyrights reserved by C.C. Cheung 2003.
Conditionals
Operators
Standard Forms
if
if (Boolean-expression) {
statement;
}
if (Boolean-expression) {
statement1;
} else {
statement2;
}
?:
Boolean-expression ? thenVal1 : elseVal2;
Switch
Switch (someInt) {
case val1: statement1; break;
case val2: statement2; break;
default: statementN;
}
INE2720 – Web Application Software Development
6
All copyrights reserved by C.C. Cheung 2003.
Reference Types
Values that are objects are known as
reference values or references.
Any non-primitive variables are known
as objects and can be treated as
pointers.
Java forbids dereferencing pointers.
– Given a referenced object.
– A method cannot modify a reference so as
to refer to another object.
INE2720 – Web Application Software Development
8
All copyrights reserved by C.C. Cheung 2003.
Arrays
Accessing arrays
– Access arrays by supplying the index in square brackets after the
variable name, variableName[index]
– The first index is 0, not 1
Example
– Here, the argument to main is an array of Strings called args
public class Test {
public static void main(String[] args) {
System.out.println("First argument: " + args[0]);
}
}
> javac Test.java
> java Test Hello There
First argument is Hello
INE2720 – Web Application Software Development
9
All copyrights reserved by C.C. Cheung 2003.
The Array length Field
Arrays have a built-in field called length that stores the size of
the array
– The length is one bigger than the biggest index, due to the fact
that the index starts at 0
Example
public class Test2 {
public static void main(String[] args) {
System.out.println("Number of args is " + args.length);
}
}
> javac Test2.java
> java Test2
Number of args is 0
> java Test2 Hello There
Number of args is 2
INE2720 – Web Application Software Development
10
All copyrights reserved by C.C. Cheung 2003.
Building Arrays
Arrays can be built in a one-step or two-step
process
1 . The one-step process is of the fo
l l owing form
:
type[] var = { val1, val2, ... , valN };
For example:
int[] values = { 10, 100, 1000 };
Point[] points = { new Point(0, 0),
new Point(1, 2), ... };
INE2720 – Web Application Software Development
11
All copyrights reserved by C.C. Cheung 2003.
Building Arrays, cont.
2.
With the two-step process, first allocate an array of references:
type[] var = new type[size];
For example:
int[] values = new int[7];
Point[] points = new Point[someArray.length];
–
–
For primitive data types, each array cell is assigned a default value
For object data types, each array cell is a reference (initially set to null)
Second, populate the array
points[0] = new Point(...);
points[1] = new Point(...);
...
INE2720 – Web Application Software Development
12
All copyrights reserved by C.C. Cheung 2003.
Multidimensional Arrays
Multidimensional arrays are implemented as
an array of arrays
int[][] twoD = new int[64][32];
String[][] cats = { { "Caesar", "blue-point" },
{ "Heather", "seal-point" },
{ "Ted",
"red-point" } };
Note: the number of elements in each row (dimension)
need not be equal
int[][] irregular = { { 1 }, { 2, 3, 4},
{ 5 }, { 6, 7 } };
INE2720 – Web Application Software Development
13
All copyrights reserved by C.C. Cheung 2003.
TriangleArray, Example
public class TriangleArray {
public static void main(String[] args) {
int[][] triangle = new int[10][];
for(int i=0; i<triangle.length; i++) {
triangle[i] = new int[i+1];
}
for (int i=0; i<triangle.length; i++) {
for(int j=0; j<triangle[i].length; j++) {
System.out.print(triangle[i][j]);
}
System.out.println();
}
}
}
INE2720 – Web Application Software Development
14
> java TriangleArray
0
00
000
0000
00000
000000
0000000
00000000
000000000
0000000000
All copyrights reserved by C.C. Cheung 2003.
Wrapper Classes
Each primitive data type has a corresponding
object (wrapper class)
Primitive
Data Type
byte
short
int
long
float
double
char
boolean
Corresponding
Object Class
Byte
Short
Integer
Long
Float
Double
Character
Boolean
– The data is stored as an immutable field of the object
INE2720 – Web Application Software Development
15
All copyrights reserved by C.C. Cheung 2003.
Wrapper Uses
Defines useful constants for each data type
– For example,
Integer.MAX_VALUE
Float.NEGATIVE_INFINITY
Convert between data types
– Use parseXxx method to convert a String to the corresponding
primitive data type
try {
String value = "3.14e6";
double d = Double.parseDouble(value);
} catch (NumberFormatException nfe) {
System.out.println("Can't convert: " + value);
}
INE2720 – Web Application Software Development
16
All copyrights reserved by C.C. Cheung 2003.
Wrappers: Converting
Strings
Data Type
byte
new
short
new
int
new
long
new
float
new
double
new
Convert String using either …
Byte.parseByte(string )
Byte(string ).byteValue()
Short.parseShort(string )
Short(string ).shortValue()
Integer.parseInteger(string )
Integer(string ).intValue()
Long.parseLong(string )
Long(string ).longValue()
Float.parseFloat(string )
Float(string ).floatValue()
Double.parseDouble(string )
Double(string ).doubleValue()
INE2720 – Web Application Software Development
17
All copyrights reserved by C.C. Cheung 2003.
Error Handling: Exceptions
In Java, the error-hand
l ing system is based on
exceptions
– Exceptions must be handed in a try/catch block
– When an exception occurs, process flow is immediately
transferred to the catch block
Basic Form
try {
statement1;
statement2;
...
} catch(SomeException someVar) {
handleTheException(someVar);
}
INE2720 – Web Application Software Development
18
All copyrights reserved by C.C. Cheung 2003.
Exception Hierarchy
Simplified Diagram of Exception Hierarchy
Throwable
Exception
…
IOException
INE2720 – Web Application Software Development
Error
RuntimeException
19
All copyrights reserved by C.C. Cheung 2003.
Throwable Types
Error
– A non-recoverab
l e prob
l em that shou
l d not be
caught (OutOfMemoryError, StackOverfl owError,
…)
Exception
– An abnorma
l condition that shou
l d be caught and
hand
l ed by the programmer
RuntimeException
– Specia
l case; does not have to be caught
– Usua
l l y the resu
l t of a poorl y written program
(integer division by zero, array out-of-bounds, etc.)
A RuntimeException is considered a bug
INE2720 – Web Application Software Development
20
All copyrights reserved by C.C. Cheung 2003.
Multiple Catch Clauses
A sing
l e try can have more that one catch cl ause
try {
...
} catch (ExceptionType1 var1) {
// Do something
} catch (ExceptionType2 var2) {
// Do something else
}
– If multiple catch clauses are used, order them from the
most specific to the most general
– If no appropriate catch is found, the exception is handed to
any outer try blocks
If no catch clause is found within the method, then the
exception is thrown by the method
INE2720 – Web Application Software Development
21
All copyrights reserved by C.C. Cheung 2003.
Try-Catch, Example
...
BufferedReader in = null;
String lineIn;
try {
in = new BufferedReader(new FileReader("book.txt"));
while((lineIn = in.readLine()) != null) {
System.out.println(lineIn);
}
in.close();
} catch (FileNotFoundException fnfe ) {
System.out.println("File not found.");
} catch (EOFException eofe) {
System.out.println("Unexpected End of File.");
} catch (IOException ioe) {
System.out.println("IOError reading input: " + ioe);
ioe.printStackTrace(); // Show stack dump
} – Web Application Software Development
INE2720
22
All copyrights reserved by C.C. Cheung 2003.
The finally Clause
After the fina
l catch cl ause, an optiona
l finally
cl ause may be defined
The finally cl ause is a
l ways executed, even if the
try or catch b
l ocks are exited through a break,
continue, or return
try {
...
} catch (SomeException someVar) {
// Do something
} finally {
// Always executed
}
INE2720 – Web Application Software Development
23
All copyrights reserved by C.C. Cheung 2003.
Thrown Exceptions
If a potentia
l exception is not hand
l ed in the method,
then the method must decl are that the exception can
be thrown
public SomeType someMethod(...) throws SomeException {
// Unhandled potential exception
...
}
– Note: Multiple exception types (comma separated) can be
declared in the throws clause
Exp
l icitl y generating an exception
throw new IOException("Blocked by firewall.");
throw new MalformedURLException("Invalid protocol");
INE2720 – Web Application Software Development
24
All copyrights reserved by C.C. Cheung 2003.
Summary
Discuss Primitive and Object types
Address the basic Java syntax
Arrays have a pub
l ic length data fie
l d
Use the wrapper lc asses to
:
– Convert primitive data types to objects
– Convert string to primitive data types
Code that may give rise to an exception must be in a
try/catch b
l ock or the method must throw the
exception
– The finally clause is always executed regardless how the
try block was exited
INE2720 – Web Application Software Development
25
All copyrights reserved by C.C. Cheung 2003.
References
CWP2: Chapter 8
http://java.sun.com/docs/books/jls/
The End.
Thank you for patience!
INE2720 – Web Application Software Development
26
All copyrights reserved by C.C. Cheung 2003.