Title: Basic Java Syntax
1Basic Java Syntax
- INE2720
- Web Application Software Development
- Essential Materials
2Outline
- 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
3Primitive Types
- Java has two fundamental kinds of data types
Primitive and Reference - Primitive are those types not objects
- Boolean true / false
- char 16-bit unsigned integer representing a
Unicode character. - byte 8-bit, signed, twos complement integer.
- short 16-bit, signed, twos complement integer.
- int 32-bit, signed, twos complement integer.
- long 64-bit, signed, twos complement.
- float 32-bit floating-point, double 64-bit fp.
4Primitive-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
5Operators
6Conditionals
7Iterations / Loops
8Reference 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.
9Arrays
- Accessing arrays
- Access arrays by supplying the index in square
brackets after the variable name,
variableNameindex - 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 "
args0) -
-
- gt javac Test.java
- gt java Test Hello There
- First argument is Hello
10The 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) -
-
- gt javac Test2.java
- gt java Test2
- Number of args is 0
- gt java Test2 Hello There
- Number of args is 2
11Building Arrays
- Arrays can be built in a one-step or two-step
process - The one-step process is of the following form
- type var val1, val2, ... , valN
- For example
- int values 10, 100, 1000
- Point points new Point(0, 0),
- new Point(1, 2), ...
12Building Arrays, cont.
- With the two-step process, first allocate an
array of references - type var new typesize
- For example
- int values new int7
- Point points new
PointsomeArray.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
- points0 new Point(...)
- points1 new Point(...)
- ...
13Multidimensional Arrays
- Multidimensional arrays are implemented as an
array of arrays int twoD new
int6432 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
14TriangleArray, Example
- public class TriangleArray
- public static void main(String args)
- int triangle new int10
- for(int i0 ilttriangle.length i)
- trianglei new inti1
-
- for (int i0 ilttriangle.length i)
- for(int j0 jlttrianglei.length j)
- System.out.print(triangleij)
-
- System.out.println()
-
-
gt java TriangleArray 0 00 000 0000 00000 000000 0
000000 00000000 000000000 0000000000
15Wrapper Classes
- Each primitive data type has a corresponding
object (wrapper class) - The data is stored as an immutable field of the
object
16Wrapper Uses
- Defines useful constants for each data type
- For example, Integer.MAX_VALUE Float.NEGATIV
E_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)
17Wrappers Converting Strings
18Error Handling Exceptions
- In Java, the error-handling 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)
-
19Exception Hierarchy
- Simplified Diagram of Exception Hierarchy
Throwable
Error
Exception
IOException
RuntimeException
20Throwable Types
- Error
- A non-recoverable problem that should not be
caught (OutOfMemoryError, StackOverflowError, ) - Exception
- An abnormal condition that should be caught and
handled by the programmer - RuntimeException
- Special case does not have to be caught
- Usually the result of a poorly written program
(integer division by zero, array out-of-bounds,
etc.) - A RuntimeException is considered a bug
21Multiple Catch Clauses
- A single try can have more that one catch clause
- 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
try ... catch (ExceptionType1 var1) //
Do something catch (ExceptionType2 var2) //
Do something else
22Try-Catch, Example
- ...
- BufferedReader in null
- String lineIn
- try
- in new BufferedReader(new FileReader("book.tx
t")) - 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
-
23The finally Clause
- After the final catch clause, an optional
finally clause may be defined - The finally clause is always executed, even if
the try or catch blocks are exited through a
break, continue, or return
try ... catch (SomeException someVar)
// Do something finally // Always executed
24Thrown Exceptions
- If a potential exception is not handled in the
method, then the method must declare 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 - Explicitly generating an exception
- throw new IOException("Blocked by
firewall.")throw new MalformedURLException("Inv
alid protocol")
25Summary
- Discuss Primitive and Object types
- Address the basic Java syntax
- Arrays have a public length data field
- Use the wrapper classes 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 block or the method must throw the
exception - The finally clause is always executed regardless
how the try block was exited
26References
- CWP2 Chapter 8
- http//java.sun.com/docs/books/jls/
- The End.
- Thank you for patience!