Presentation is loading. Please wait.

Presentation is loading. Please wait.

Session 5: Array, Generic, Exception Handling.

Similar presentations


Presentation on theme: "Session 5: Array, Generic, Exception Handling."— Presentation transcript:

1 Session 5: Array, Generic, Exception Handling.
Java Training Session 5: Array, Generic, Exception Handling.

2 Arrays A group of variables containing values that all have the same type Arrays are fixed-length entities In Java, arrays are objects, so they are considered reference types But the elements of an array can be either primitive types or reference types (including arrays)

3 Arrays (contd.) We access the element of an array using the following syntax nameOfArray [ index ] Here, “index” must be a nonnegative integer “index” can be int, byte, short or char but not long In Java, every array knows its own length. The length information is maintained in a public final int member variable called length.

4 Declaring and Creating Arrays
int c[ ] = new int [12]; Here, ‘c’ is a reference to an integer array ‘c’ is now pointing to an array object holding 12 integers Like other objects arrays are created using “new” and are created in the heap “int c[ ]” represents both the data type and the variable name. Placing number here is a syntax error. int c[12]; // syntax error/compiler error

5 Declaring and Creating Arrays (contd.)
int[ ] c = new int [12]; Here, the data type is more evident i.e. “int[ ]” But does the same work as int c[ ] = new int [12]; Is there any difference between the above two approaches? Yes. See the next slide.

6 Declaring and Creating Arrays (contd.)
int c[ ], x; Here, ‘c’ is a reference to an integer array ‘x’ is just a normal integer variable int[ ] c, x; Here, ‘c’ is a reference to an integer array (same as above) But, now ‘x’ is also a reference to an integer array

7 Using an Array Initializer
We can also use an array initializer to create an array int n[ ] = {10, 20, 30, 40, 50}; The length of the above array is 5 n[0] is initialized to 10, n[1] is initialized to 20, and so on The compiler automatically performs a “new” operation taking the count information from the list and initializes the elements properly.

8 Arrays of Primitive Types
When created by “new”, all the elements are initialized with default values byte, short, char, int, long, float and double are initialized to zero boolean is initialized to false This happens for both member arrays and local arrays

9 Arrays of Reference Types
String str[ ] = new String[3]; Only 3 String references are created Those references are initialized to “null” by default Both for member arrays and local arrays Need to explicitly create and assign actual String objects in the above three positions. str[0] = new String(“Hello”); str[1] = “World”; str[2] = “I” + “ Like” + “ Java”;

10 Passing Arrays to Methods
double temperature[ ] = new double[24]; modifyArray( temperature ); Here, “modifyArray” is declared as void modifyArray( double d[ ] ) Changes made to the elements of ‘d’ inside “modifyArray” is visible and reflected in the original “temperature” array. But inside “modifyArray” if we create a new array using “new” and assign it to ‘d’ then ‘d’ will point to the newly created array and changing its elements will have no effect on “temperature” (see next slide).

11 Passing Arrays to Methods (contd.)
So, we can say that while passing array to methods, changing the elements is visible, but changing the array reference itself is not visible. void modifyArray( double d[ ] ) { d[0] = 1.1; // visible to the caller } d = new double [ 10 ]; d[0] = 1.1; // not visible to the caller

12 Multidimensional Arrays
Can be termed as array of arrays. int b[ ][ ] = new int[3][4]; Length of first dimension = 3 b.length equals 3 Length of second dimension = 4 b[0].length equals 4 int[ ][ ] b = new int[3][4]; Here, the data type is more evident i.e. “int[ ][ ]”

13 Multidimensional Arrays (contd.)
int b[ ][ ] = { { 1, 2, 3 }, { 4, 5, 6 } }; b.length equals 2 b[0].length and b[1].length equals 3 All these examples represent rectangular two dimensional arrays where every row has same number of columns. Java also supports jagged array where rows can have different number of columns (see next slide).

14 Multidimensional Arrays (contd.)
Example - 1 int b[ ][ ]; b = new int[ 2 ][ ]; b[ 0 ] = new int[ 2 ]; b[ 1 ] = new int[ 3 ]; b[0][2] = 7; // will throw an exception Example – 2 int b[ ][ ] = { { 1, 2 }, { 3, 4, 5 } }; b[0][2] = 8; // will throw an exception In both cases b.length equals 2 b[0].length equals 2 b[1].length equals 3 Array ‘b’ Col 0 Col 1 Col 2 Row 0 Row 1 b[0][2] does not exist!!

15 Let’s Try!! A very easy one!!
Write code for matrix addition and multiplication.

16 Matrix Addition Output:
package array; public class MatrixTest{ public static void main(String[] args) { int matrixA[][] = {{1, 2, 3}, {10, 20, 30}, {40, 50, 60}}; intmatrixB[][] = new int[3][3]; matrixB[0][0] = 0; matrixB[0][1] = 1; matrixB[0][2] = 2; matrixB[1][0] = 0; matrixB[1][1] = 10; matrixB[1][2] = 20; MatixA: MatixB: Result: matrixB[2][0] = 30; matrixB[2][1] = 40; matrixB[2][2] = 50; int[][] matrixResult = new int[3][3]; /* Write rest of the code ... */ }

17 Using Command-Line Arguments
java MyClass arg1arg2 … argN Words after the class name are treated as command-line arguments by “java” “java” creates a separate String object containing each command-line argument, places them in a String array and supplies that array to “main” That’s why we have to have a String array parameter (String args[ ]) in “main”. We do not need a “argc” type parameter (for parameter counting) as we can easily use “args.length” to determine the number of parameters supplied.

18 Using Command-Line Arguments (contd.)
public class MyClass { public static void main ( String args[ ] ) System.out.println( args.length ); for( int i = 0; i < args.length; i++) System.out.println( args[i] ); } Sample Execution – 1 java MyClass Hello World Output: 2 Hello World Sample Execution – 2 java MyClass Hello 2 you 3 you

19 Generics Some times we may need to implement same algorithm for different types of variable. Consider a Stack or Queue implementation. One may need a stack of Double while other may be need stack of Integer. But the algorithm is same inside. Last In First Out. Writing separate implementations for Integer and double is waste of time.

20 Generics Solution is generic.
Conception is we will create a algorithm related object with what type elements the algorithm will perform on. Ex. ArrayList, VectorList Our discussion will be limited in using generic class in Java Colloection.

21 Example Output: Length: 3 Element(0): 13 Element(1): 19 List elements:
ArrayList<Integer> list = new ArrayList<Integer>(); list.add(13); list.add(17); list.add(19); System.out.println("Length: " + list.size()); System.out.println("Element(0): " + list.get(0)); System.out.println("Element(1): " + list.get(2)); System.out.println("List Elements:"); for (Integer integer : list) { System.out.println(integer); } Output: Length: 3 Element(0): 13 Element(1): 19 List elements: 13 17 19

22 Example ArrayList<Double>doubleList = new ArrayList<Double>(); doubleList.add(13.12); doubleList.add(17.2); doubleList.add(19.123); doubleList.add(23.12); System.out.println("Length: " + doubleList.size()); System.out.println("Element(0): " + doubleList.get(0)); System.out.println("Element(1): " + doubleList.get(2)); System.out.println("List Elements:"); for (Double d : doubleList) { System.out.println(d); } Output: Length: 4 Element(0): 13.12 Element(1): List Elements: 13.12 17.2 19.123 23.12

23 Generics No wonder generics is one of the very interesting features of java. For more on generics please follow the oracle java tutorial - There is a book name Java Generics. You can give it a try.

24 Exception Handling Say we have an array of size 3. Like
String str[] = new String[3]; But we accessed str[4]; then java will throw an exception nameArrayIndexOutOfBoundsException How to handle those?

25 try { } catch try { String str[] = new String[3]; str[4] = "123"; //will throw exception. System.out.println("This line won't be executed"); System.out.println("This line too"); int b = 100; System.out.println("Value of b: " + b + " but this won't be executed too"); } catch (ArrayIndexOutOfBoundsExceptionaioobe) { System.err.println("Improper access."); }

26 Exception-Handling Overview
Enables programmers to remove error-handling code from the “main line” of the program’s execution Improves program clarity Enhances modifiability Java forces the programmer to be prepared for certain types of problems so that sudden occurrence of such problems do not cause significant damage.

27 Exception-Handling Overview (contd.)
If a single-threaded program does not handle an exception, then it will be terminated immediately. If a multi-threaded program does not handle an exception, then it may not be terminated, but may show unusual behaviors. So, it is better to be prepared for different types of exceptions.

28 Syntax A single “try” block may be followed by zero or multiple “catch” blocks. If no “catch” block is provided, then a “finally” block must be provided for a “try” block. If no exception is thrown in the “try” block, then all the “catch” blocks are skipped and execution resumes after the last “catch” block. If an exception is thrown inside the “try” block, then execution immediately leaves the “try” block and Java searches for an appropriate “catch” handler capable of handling the exception from top to bottom. The first matching “catch” block is executed. All other “catch” blocks at the same level are skipped. The necessary information about the exception is wrapped inside an exception object and supplied to the corresponding “catch” handler. After all, Java does not do anything without objects. try { // statements that may throw exceptions } catch(ExceptionType1 refName) // statements to process ExceptionType1 catch(ExceptionType2 refName) // statements to process ExceptionType2 catch(ExceptionTypeNrefName) // statements to process ExceptionTypeN

29 Some Common Exceptions
Exception classes in the Java API ArrayIndexOutOfBoundsException NullPointerException ClassCastException ArithmeticException InputMismatchException FileNotFoundException InterruptedException IOException (package java.io) Exception (package java.lang) And many more. You can also develop your own exception classes.

30 Throwing an Exception You can throw an exception using the “throw” statement. throw new Exception(); You can only throw an object of a class which is Throwable, i.e. a subclass of the Java API class Throwable. You can also rethrow a caught exception. It will be handled by the next outer level exception handler (if one is present) try { } catch(Exception e) { throw e; }

31 Using the throws Clause
If a method does not want to handle an exception then it must declare that it may throw the exception using the throws clause void methodName( ) throws Exception1, Exception2 That means Java employs a catch or declare strategy in exception-handling If you do not catch a particular exception, you must declare it There is a little deviation from this rule (see the discussion on unchecked exceptions later)

32 Exception in Constructor
If a exception is thrown in constructor then the object is not constructed!!

33 Let’s Try!! Write a Student class in student package.
Student has two fields. Name Marks Throw Exceptions in time of creation of student If the Name is null or empty string with message “Student name can not be empty” If Mark is less then 0 or greater then 100 with message “Invalid marks”

34 Output Output: Error occured: Student name can not be empty
try { Student student = new Student("", 10); System.out.println("This line won't be executed."); System.out.println(student); } catch (Exception ex) { System.err.println("Erroroccured: " + ex.getMessage()); } Student student = new Student("Abcd", 10000); Student student = new Student("Abcd", 97); Output: Error occured: Student name can not be empty [Name: Abcd, 97] Invalid Marks

35 When to Use Exception Handling
Exception handling is designed to process synchronous errors, which occur when a statement executes Out-of-range array indices Arithmetic overflow Division by zero Thread interruption etc.

36 Java Exception Hierarchy (Partial List)
Throwable Exception Error RuntimeException IOException OutOfMemoryError ThreadDeath ClassCastException NullPointerException

37 Checked vs. Unchecked Exceptions
Must be caught (using try … catch) or declared using throws If not handled properly, Java compiler (javac) issues compiler error Example: All classes that inherit from class Exception but not class RuntimeException Unchecked Exceptions May or may not be handled Handling not enforced by the Java compiler All exception types that are direct or indirect subclasses of class RuntimeException ArrayIndexOutOfBoundsException, ArithmeticException etc. Classes that inherit from class Error

38 Arrangement of catch Blocks
catch blocks for a try block must be arranged from specific to general order If we place a superclass exception before a subclass exception then Java compiler (javac) will flag it as an error Consider the following exception inheritance - java.lang.Exception java.io.IOException java.io.EOFException Now, in order to handle exceptions of these types, we have to catch them from most specific to more general case (see next slide)

39 Arrangement of catch Blocks (contd.)
try { // statements that may throw exceptions } catch(EOFException eofe) { catch(Exception e) { // this catch block should be the last catch block catch(IOException ioe) { Invalid ordering of catch blocks try { // statements that may throw exceptions } catch(EOFException eofe) { catch(IOException ioe) { catch(Exception e) { Correct ordering of catch blocks

40 finally block It is an optional block/clause
Must be placed after the last catch block Codes present in this block are always executed whether exception occurs or not inside the try block A finally block will also execute if a try block exits by using a return, break or continue statement Generally used to release system resources like closing files, sockets etc. The finally block will not execute if we use System.exit inside the try block or a catch block that gets executed after an exception occurs

41 Declaring New Exception Types
// File: StackException.java public class StackException extends Exception { public StackException( ) { super( “Stack exception occurred” ); } public StackException( String message ) { super( message );


Download ppt "Session 5: Array, Generic, Exception Handling."

Similar presentations


Ads by Google