Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Topics Introduction Types of Errors Exceptions Exception Handling
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Index Exception handling Exception In Java Exception Types
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
1 More on Threads b b A section of code executed independently of other threads written within a single program. b b Java threads can access global data;
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
1 Java - Threads A thread is an individual flow of control within a larger program. A program which is running more than one thread is said to be multithreaded.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Exception Handling 1. Introduction Users may use our programs in an unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Object Oriented Programming with Java (150704).  Throwable Exception (This class will catch exceptions generated by prog.) (Create your own custom exception.
Slides Credit Umair Javed LUMS Web Application Development.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
COMP Exception Handling Yi Hong June 10, 2015.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading in JAVA
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Classes, Interfaces and Packages
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Chapter 14 – Exception Handling
Chapter 10 – Exception Handling
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Multithreading in Java
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exception Handling Chapter 9.
Java Programming Language
EXCEPTION HANDLING OR ERROR HANDLING.
Exception Handling Chapter 9 Edited by JJ.
Web Design & Development Lecture 7
Managing Errors and Exceptions
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Chapter 12 Exception Handling and Text IO Part 1
Presentation transcript:

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.

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.

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.

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.

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.

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

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.

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.

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”);} }

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 ); }}

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); } }

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.

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

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.

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.

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");} }

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(); } }

Inside A Procedure A Finally completed Exception is caught Inside B Procedure B Finally completed Inside C Procedure C Finally completed

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.

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.

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.

InterruptedException : One thread has been interrupted by another thread. NoSuchFieldException: A requested field does not exist. NoSuchMethodException : A requested method does not exist.

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.

To implement access class classname[extends superclass] [implements interface [,interface…]] {//class body…. } Think…….. Can we use public as access? Can we extend an interface?

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();}

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

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.

Java applet net awt io util lang

Colour Graphics Font Image awt Java Use import java.awt.*;

Creating a package: package firstPackage; public class FirstClass {……. body of class….. } Accessing the package: Import firstPackage.*;

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?

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(); }

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'); } }

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 }

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………….

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

The output is: Mondays are bad. Midweek days are so-so. Fridays are better. Weekends are best.

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….)

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.

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.

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

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.

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.

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.

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....

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...."); } }

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!"); // } } }

Main Reference: Patrick Naughton and Herbert Schildt, The Complete Reference Java 2, Third Edition, Tata McGraw Hill Pub., Visit pritisajja.info to download this show….