Download presentation
Presentation is loading. Please wait.
Published byRaquel Shandy Modified over 9 years ago
2
Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java, S P University.
3
An exception is an abnormal condition that arise in a code sequence at run time. An exception therefore, is a run time error. If the facility of exception handling is not supported by a programming environment, through error code one can handle error, which is a cumbersome task. Java solves this problem by offering run time management of errors. A java exception is an object that describes an exceptional condition that has occurred in a piece of a code.
4
When an exception condition arise, an object representing that exception is created and thrown in the method that cause the error. This method may choose to handle that exception or pass it to other method. Not only by a run time system of Java, bur manually also an exception is created and thrown.
5
Java exception handling is managed through five key words: – try, catch, throw, throws and finally. Program statement which you’d like to monitor are enclosed in try (and catch) block. If any exception occurs, within that try block, it is thrown. Your code can catch the exception thrown and takes necessary action. System generated exception are thrown automatically by the java run time system. To manually throw the exception, use the keyword throw. Any exception which must be thrown out of the method, must be specified with the throws clause. Any code that absolutely must be executed before a method returns, is put in finally block.
6
Here is the general form: try{ // block of code to monitor } catch( Exceptiontype1 ob1) {//exception handling code…1} catch( Exceptiontype1 ob2) {//exception handling code…2} //… Finally {//… must be executed before return} Here exception type is the type of exception that has occurred.
7
All exception types are subclasses of the built in class Throwable. Thus Throwable is at the top of the exception class hierarchy. Immediately below this Throwable into two branches. One branch is headed by Exception. And there is an important subclass of Exception that is called RuntimeException. The another branch is Error, which defines exceptions that are not expected to be caught under normal conditions. Error is used by the Java run time system to indicates errors. Eg. Stack overflow run time error given by the Java. Throwable Exception RuntimeException Error
8
class ex1{ public static void main(String args[]){ int d=0; int a=42/0; }} Results in javac ex1.java ex1.java:4: Arithmetic exception. int a=42/0; ^ When java run time system detects the attempt to divide by zero, it constructs a new exception and then throws the exception (outside the method). This cause the execution of the program stopped. That is such exception must be caught within the program and dealt with immediately. When java run time system detects the attempt to divide by zero, it constructs a new exception and then throws the exception (outside the method). This cause the execution of the program stopped. That is such exception must be caught within the program and dealt with immediately.
9
Here we have not specified any such exception handling code, so the exception is caught by a default handler of the Java. Any exception that that is not caught by your program will ultimately processed by the default handler. The default handler displays a string describing the exception and terminates the program.
10
class ex2{ public static void main(String args[]){ int d, a try { d=0; a=42/d; System.out.println(“message…”); } catch (ArithmeticException e) { System.out.println(“Division by 0”);} }
11
class ex3{ public static void main(String args[]){ int d, a; try { d=0; a=42/d; System.out.println("No..."); } catch (ArithmeticException e) { System.out.println("Division by 0"); System.out.println("System will say :" +e); a=0;//setting a==0 and continue.... } System.out.println("a:= " + a ); }}
12
class ex4{ public static void main(String args[]){ int a[] ={5,10}; int b=5; try { int x=a[1]/(b-a[0]);} // change it to int x=a[2]/b-a[1] catch(ArithmeticException e) {System.out.println("Division by zero...");} catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index error...");} catch(ArrayStoreException e) {System.out.println(“Wrong data type...");} int y=a[1]/a[0]; System.out.println("Y is = "+y); } }
13
So far, you have only been catching exceptions that are thrown by java run time system. The general form of throw is – Throw ThrowableInstance Here the ThrowableInstance must be an object of type throwable or a subclass of throwable. Simple types such as integer, char and String are non- throwable. There are two way you can obtain a throwable object – Using a parameter into a catch statement – Creating one with new operator.
14
class ThrowDemo{ static void demoproc(){ try{ throw new NullPointerException("Demo"); } catch (NullPointerException e){ System.out.println("Caught inside demo"); throw e;} } public static void main(String args[]){ try{ demoproc(); } catch (NullPointerException e){ System.out.println("Recaught: "+e); } }} Caught inside demo Recaught: java.lang.NullPointerException: Demo Caught inside demo Recaught: java.lang.NullPointerException: Demo
15
If a method is capable of causing an exception that it does not handle, it must specify them with the throws statement. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions except Error type or RuntimeException, or any of their subclasses.
16
When exceptions are thrown, execution may take non-linear path(disturbed). The finally block will execute weather or not an exception is thrown. This can be useful in operation like closing the files and releasing the resources before returning. The finally clause is optional, however one try statement requires at least one catch or one finally clauses. If a finally block is attached with a try, it will be executed upon conclusion of try.
17
class FinallyDemo{ static void procA(){ try{ System.out.println("Inside A"); throw new RuntimeException("Demo"); }finally {System.out.println("Procedure A Finally completed");} } static void procB(){ try{ System.out.println("Inside B"); return; } finally {System.out.println("Procedure B Finally completed");} }
18
static void procC(){ try{ System.out.println("Inside C"); } finally{System.out.println("Procedure C Finally completed");} } public static void main(String args[]){ try{ procA(); }catch (Exception e){ System.out.println("Exception is caught");} procB(); procC(); } }
19
Inside A Procedure A Finally completed Exception is caught Inside B Procedure B Finally completed Inside C Procedure C Finally completed
20
ArithmeticException: Arithmetic error, such as divide by zero. ArrayIndexOutOf BoundsException: Using array subscript out of bound ArrayStoreException: Assignment to an array element of an incompatible type ClassCastException: Invalid Cast. IllegalArgumentException: Illegal argument used to invoke a method.
21
NegativeArraySizeException : Array created with a negative size. NumberFormatException : Invalid conversion of string to a number format. StringIndexOutOfBounds : Attempt to index outside the bounds of a string.
22
ClassNotFoundException : Class not found. ClassNotSupportedException: Attempt to clone an object that doesnot implement the cloneable interface. InstantiationException : Attempt to create an object of an abstract class. IllegalAccessException : Access to a class is denied.
23
InterruptedException : One thread has been interrupted by another thread. NoSuchFieldException: A requested field does not exist. NoSuchMethodException : A requested method does not exist.
24
An interface is basically a kind of class. Like classes interface contains methods and variables. The interface defines the abstract method and final fields only. That means interfaces do not supply any code to implement these methods. It is necessary to implement an interface and it is the responsibility of a class which wants to use it.
25
To implement access class classname[extends superclass] [implements interface [,interface…]] {//class body…. } Think…….. Can we use public as access? Can we extend an interface?
26
class Student{ int rollNumber; void getNumber(int n) { rollNumber=n;} void putNumber() {System.out.println(“RollNo:“ +rollNumber);} } class Test extends Students { float part1, part2; void getMarks(float m1, float m2 ) {part1=m1; part2=m2;} void putMarks() { System.out.println(“Marks Obtained”); System.out.println(“ Part1= “ + part1); System.out.println(“ Part2= “ + part2); }} interface Sports{ float sportWt=6.0; void putWt();}
27
class Results extends Test implements Sports{ float total; public void putWt (){System.out.println(“SporWt= “+ sportWt);} void display () { putNumber(); putMarks(); PutWt(); total= part1+part2+sportWt; System.out.println(“Total= “+ total);}} class Hybrid{ public static void main(String args[]){ Results student1= new Results(); student1.getNumber(1234); student1.getMarks(27.5, 33.0); student1.display(); }} Student Test Result Sports
28
By organizing classes into packages achieve the following benefits: – Classes contained in can be easily reused. – Two classes in two different package can have same name. – Hides classes and make program simple and modular. – Provides a way for separating design from coding.
29
Java applet net awt io util lang
30
Colour Graphics Font Image awt Java Use import java.awt.*;
31
Creating a package: package firstPackage; public class FirstClass {……. body of class….. } Accessing the package: Import firstPackage.*;
32
package package1; public class ClassA{ public void displayA() {System.out.println("Class A");} } //-------------- end of ClassA --------- Make a directory called package1 and Write this file under the name ClassA.java and compile it. It will not run. WHY?
33
Go to main/higherlevel directory (contains subditectory as package1) and write, compile and execute the following file. import package1.ClassA; class PackageTest1{ public static void main(String args[]){ ClassA ObjectA = new ClassA(); ObjectA.displayA(); }
34
import java.io.*; class Read{ public static void main(String args[]) throws IOException{ char c; BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter characters:, 'q' to quit"); do{ c=(char)br.read(); System.out.println(c); } while (c!='q'); } }
35
An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week. Because they are constants, the names of an enum type's fields are in uppercase letters. For example, no od days in week can be defined as follows: public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
36
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } public class EnumTest { Day day; public EnumTest(Day day) { this.day = day; } public void tellItLikeItIs() { switch (day) { case MONDAY: System.out.println("Mondays are bad."); break; case FRIDAY: System.out.println("Fridays are better."); break; case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); break; default: System.out.println("Midweek days are so-so."); break; } } // ond of tell like I method………….
37
public static void main(String[] args) { EnumTest firstDay = new EnumTest(Day.MONDAY); firstDay.tellItLikeItIs(); //-------------------- EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); thirdDay.tellItLikeItIs(); EnumTest fifthDay = new EnumTest(Day.FRIDAY); fifthDay.tellItLikeItIs(); EnumTest sixthDay = new EnumTest(Day.SATURDAY); sixthDay.tellItLikeItIs(); EnumTest seventhDay = new EnumTest(Day.SUNDAY); seventhDay.tellItLikeItIs(); } // end of main } // end of class
38
The output is: Mondays are bad. Midweek days are so-so. Fridays are better. Weekends are best.
39
The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system. //for (Day day : Day.values()) { System.out.printf(p);} (not checked yet….)
40
Thread is a short form of Threads of control. Thread of control is path taken by program during execution. Having multiple threads of control is like executing task from two lists. Each thread begins execution at a predefined well known location eg. main(). Threads are single-minded in their purpose, always executing the next statement in the sequence. Thread is a short form of Threads of control. Thread of control is path taken by program during execution. Having multiple threads of control is like executing task from two lists. Each thread begins execution at a predefined well known location eg. main(). Threads are single-minded in their purpose, always executing the next statement in the sequence.
41
Each thread executes its code independently of other threads in the program. The threads have access to various types of data. That is for each independent thread, there is separate list of private/local variables, if they have to be shared, a copy is made. Objects and instances can be shared with permission by two or more threads. Static variables are automatically shared between threads in a Java program. Each thread executes its code independently of other threads in the program. The threads have access to various types of data. That is for each independent thread, there is separate list of private/local variables, if they have to be shared, a copy is made. Objects and instances can be shared with permission by two or more threads. Static variables are automatically shared between threads in a Java program.
42
Non Blocking I/O: when server is not available, or busy, separate thread can be extended to the task and focus can be given on other tasks. Alarms and timers: The program set the timer and continues processing. When time expires, the program receives some sort of message/signal. Independent tasks : Such as autosave in word processor Multiple CPUs
43
There are two ways to create a thread. – Extend the java.lang.Thread class – Implement the java.lang.Runnable interface. Once you have a Thread object, you call its start method to start the thread. When a thread is started, its run method is executed. Once the run method returns or throws an exception, the thread dies and will be garbage-collected. There are two ways to create a thread. – Extend the java.lang.Thread class – Implement the java.lang.Runnable interface. Once you have a Thread object, you call its start method to start the thread. When a thread is started, its run method is executed. Once the run method returns or throws an exception, the thread dies and will be garbage-collected.
44
Every Thread has a state and a Thread can be in one of these six states. new. A state in which a thread has not been started. runnable. A state in which a thread is executing. blocked. A state in which a thread is waiting for a lock to access an object. waiting. A state in which a thread is waiting indefinitely for another thread to perform an action. timed__waiting. A state in which a thread is waiting for up to a specified period of time for another thread to perform an action. terminated. A state in which a thread has exited. The values that represent these states are encapsulated in the java.lang.Thread.State enum. The members of this enum are NEW, RUNNABLE, BLOCKED, WAITING, TIMED__WAITING, and TERMINATED. Every Thread has a state and a Thread can be in one of these six states. new. A state in which a thread has not been started. runnable. A state in which a thread is executing. blocked. A state in which a thread is waiting for a lock to access an object. waiting. A state in which a thread is waiting indefinitely for another thread to perform an action. timed__waiting. A state in which a thread is waiting for up to a specified period of time for another thread to perform an action. terminated. A state in which a thread has exited. The values that represent these states are encapsulated in the java.lang.Thread.State enum. The members of this enum are NEW, RUNNABLE, BLOCKED, WAITING, TIMED__WAITING, and TERMINATED.
46
Method Return Type Description currentThread( ) Thread Returns an object reference to the thread in which it is invoked. getName( ) String Retrieve the name of the thread object or instance. start( ) void Start the thread by calling its run method. run( ) void This method is the entry point to execute thread, like the main method for applications. sleep( ) void Suspends a thread for a specified amount of time (in milliseconds). isAlive( ) boolean This method is used to determine the thread is running or not. activeCount( ) int This method returns the number of active threads in a particular thread group and all its subgroups. interrupt( ) void The method interrupt the threads on which it is invoked. yield( ) void By invoking this method the current thread pause its execution temporarily and allow other threads to execute. join( ) void This method and join(long millisec) Throws InterruptedException. These two methods are invoked on a thread. These are not returned until either the thread has completed or it is timed out respectively.
47
class MyThread extends Thread { String s=null; MyThread(String s1) { s=s1; start(); } // constructor of the thread……………….. public void run(){ System.out.println(s); } } // end of MyThread class //-------------------------------------new class------------------------------- public class RunThread{ public static void main(String args[]){ MyThread m1=new MyThread("Thread started...."); } } C:>javac RunThread.java C:>java RunThread Thread started....
48
class MyThread1 implements Runnable{ Thread t; String s=null; //constructor ------------------------------------------------------- MyThread1(String s1){s=s1; t=new Thread(this); t.start(); } //--------------------------run method------------------------------ public void run() { System.out.println(s); } } //=========================new class================ public class RunableThread{ public static void main(String args[]){ MyThread1 m1=new MyThread1("Thread started...."); } } class MyThread1 implements Runnable{ Thread t; String s=null; //constructor ------------------------------------------------------- MyThread1(String s1){s=s1; t=new Thread(this); t.start(); } //--------------------------run method------------------------------ public void run() { System.out.println(s); } } //=========================new class================ public class RunableThread{ public static void main(String args[]){ MyThread1 m1=new MyThread1("Thread started...."); } }
49
import java.io.IOException; public class Threads extends Thread{ public static void main(String[] args){ Thread th = new Thread(); System.out.println("Numbers are printing line by line after 5 seconds : "); try{ for(int i = 1;i <= 10;i++) { System.out.println(i); th.sleep(5000); } } catch(InterruptedException e){ System.out.println("Thread interrupted!"); //----------------------------------- } } }
50
Main Reference: Patrick Naughton and Herbert Schildt, The Complete Reference Java 2, Third Edition, Tata McGraw Hill Pub., 1999. Visit pritisajja.info to download this show….
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.