CSC 201 Lecture - 11
Static and Instance Methods public class MainClass { public void sort() Instance method { } public static void testMethod() Static method { } public static void main(String[] args) { Creating an object ‘m’ MainClass m = new MainClass(); m.sort(); testMethod(); }
Static and Instance methods • Instance Methods: are associated with an object and use instance variables of that object. • Static methods: They use no instance variables of any object of the class they are defined in. Static methods take all data from parameters and perform computation. • A non static method cannot be referenced from a static context, whereas static method can be referenced from a static context. • Static methods or static fields are always class members. • Non-static methods and fields are always instance members.
Another Example class staticcheck{ public static void staticMethod() {} public void nonStaticMethod() {} } public class MainClass { public static void main(String[] args){ staticcheck s = new staticcheck(); staticcheck.staticMethod(); s.nonStaticMethod(); } }
Example public class accessStaticMethod { public static void staticMethod() { System.out.println(“Here is static method access”); } public void nonStaticMethod() { System.out.println(“Cannot access non-static method:”); } public static void main(String[] args) { staticMethod(); nonStaticMethod(); } } What happens when you write nonStaticMethod() ? How to overcome this problem?
Static Variables • Usage: To define constants. Ex: Math.PI • Usually programming languages have global variables. • In case of Java, we can define static class variable in a class. A static variable like a static method is not attached to an object. • Each time you call the instance a new value of the variable is provided.
Example-Static Variable public class staticVariableDemo { static int num; staticVariableDemo() { num++; } public static void main(String[] args) { staticVariableDemo inst1 = new staticVariableDemo(); System.out.println(“Valueof num is:”+inst1.num); staticVariableDemo inst2 = new staticVariableDemo(); System.out.println(“Value of num with inst1 is:”+inst1.num); System.out.println(“Value of num with inst2 is:”+inst2.num); } }
Agenda • • • • • •
What is an exception? What happens when an exception occurs? How to catch these exceptions? Try catch block Rules in Exception Handling Sample programs – Exception Handling
Errors in Java • There are two kinds of errors: Compile-time errors and Run-time errors. • Compile-Time errors: Syntax errors. Ex: int num = 1 Error: No ‘;’. • Run time errors: An error that occurs during runtime. Ex: Divide By Zero errors, Accessing the elements of an array beyond its range, File not found etc.
Exception example program public class Main { public static void main(String[] args) { System.out.println("I want to show you a Runtime error"); int num1 = 3, num2 = 0; int result = num1 / num2; System.out.println(result); } } What is the output?
Sample Program • What happens in the following scenario? public static void main(String[] args) { Array Index out of bounds? int [] a= {1,2,3,4,5}; for(int i =0; i < 6; i++) System.out.println(“Elements of array a are “+a[i]); }
Default Exception Handling Error messages displayed : I want to show you a Runtime error Exception in thread "main" java.lang.ArithmeticException: / by zero at DivideNumbers.Main.main(Main.java:15)
Default Exception Handling Error message displayed for our Array program: Elements of an array are: 1 2 3 4 5 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at ArrayCheck.Main.main(Main.java:16)
Exception An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
Default Exception Handler • Provided by Java runtime. • Prints out exception description. • Causes the program to terminate
Catching and Handling Exceptions • Three exception handler components : the Try, catch blocks– to write an exception handler. • Try Block : The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. try { // Lines of code which may possibly // throw exception. } catch (Exception exceptionobject) { //Catches the error and explain the cause of the error. }.
Example int[] a = new int[5]; try { System.out.println(a[-1]); } catch(Exception e) {} If an exception occurs within a ‘try’ block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a ‘catch’ block after it.
Catch blocks try { ______ ______ catch (ExceptionType name) { catch (ExceptionType name) {
} } } • Each catch block is an exception handler and handles the type of exception indicated by its argument. • The catch block contains the code that is executed if and when the exception handler is invoked. • A single try block must have at least 1 or more catch blocks.
Example try catch blocks try { }catch (FileNotFoundException e) { System.out.println(“File not found exception:”); } catch( IOException e) { System.out.println(“Caught IoException:”); }