Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
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 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, two’s complement integer. – short: 16-bit, signed, two’s complement integer. – int: 32-bit, signed, two’s complement integer. – long: 64-bit, signed, two’s complement. – float: 32-bit floating-point, double: 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. Iterations / Loops Construct Standard forms while while (continueTest) { body; } do do { body; } while (continueTest); for for (init; continueTest; updateOp) { body; } INE2720 – Web Application Software Development 7 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 following 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-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); } 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-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 INE2720 – Web Application Software Development 20 All copyrights reserved by C.C. Cheung 2003. Multiple Catch Clauses A single try can have more that one catch clause 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 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 } INE2720 – Web Application Software Development 23 All copyrights reserved by C.C. Cheung 2003. Thrown 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("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 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 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.