1 / 44

BCA-307 : Object Technologies & Programming using Java

BCA-307 : Object Technologies & Programming using Java. PREPARED BY : NAVEEN NAGPAL (SENIOR ASSISTANT PROFESSOR). SYLLABUS Unit-III.

beaulieu
Download Presentation

BCA-307 : Object Technologies & Programming using Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. BCA-307 : Object Technologies & Programming using Java PREPARED BY : NAVEEN NAGPAL (SENIOR ASSISTANT PROFESSOR) DEPTT. OF COMP. SC & APPLICATIONS

  2. SYLLABUS Unit-III • Packages : Defining Package, CLASSPATH, Package naming, Accessibility of Packages , using Package Members. Interfaces: Implementing Interfaces, Interface and Abstract Classes, Extends and Implements together . Exceptions Handling : Exception , Handling of Exception, Using try-catch , Catching Multiple Exceptions , Using finally clause , Types of Exceptions, Throwing Exceptions, Writing Exception Subclasses. DEPTT. OF COMP. SC & APPLICATIONS

  3. Packages • Provides a mechanism for grouping a variety of classes and / or interfaces together. • Grouping is based on functionality. Benefits: • The classes contained in the packages of other programs can be reused. • In packages, classes can be unique compared with classes in other packages. • Packages provides a way to hide classes. DEPTT. OF COMP. SC & APPLICATIONS

  4. Packages conti… Two types of packages: 1. Java API packages 2. User defined packages Java API Packages: A large number of classes grouped into different packages based on functionality. Examples: 1. java.lang 2. java.util 3. java.io 4. java.awt 5.java.net 6.java. applet etc. DEPTT. OF COMP. SC & APPLICATIONS

  5. Accessing Classes in a Package Fully Qualified class name: Example:java.awt.Color import packagename.classname; Example: import java.awt.Color; or import packagename.*; Example: import java.awt.*; Import statement must appear at the top of the file, before any class declaration. DEPTT. OF COMP. SC & APPLICATIONS

  6. Creating Your Own Package • Declare the package at the beginning of a file using the form package packagename; Define the class that is to be put in the package and declare it public. Create a subdirectory under the directory where the main source files are stored. Store the listing as classname.java in the subdirectory created. Compile the file. This creates .class file in the subdirectory. Example: package firstPackage; public class FirstClass { //Body of the class } DEPTT. OF COMP. SC & APPLICATIONS

  7. Example1-Package package p1; public class ClassA { public void displayA( ) { System.out.println(“Class A”); } } import p1.*; Class testclass { public static void main(String str[]) { ClassA obA=new ClassA(); obA.displayA(); } } Source file – ClassA.java Subdirectory-p1 ClassA.Java and ClassA.class->p1 import p1.*; class testclass { public static void main(String str[]) { ClassAobA=new ClassA(); obA.displayA(); } } Source file-testclass.java testclass.java and testclass.class->in a directory of which p1 is subdirectory. DEPTT. OF COMP. SC & APPLICATIONS

  8. Creating Packages Consider the following declaration: package firstPackage.secondPackage; This package is stored in subdirectory named firstPackage.secondPackage. A java package can contain more than one class definitions that can be declared as public. Only one of the classes may be declared public and that class name with .java extension is the source file name. DEPTT. OF COMP. SC & APPLICATIONS

  9. Example2-Package package p2; public class ClassB { protected int m =10; public void displayB() { System.out.println(“Class B”); System.out.println(“m= “+m); } } import p1.*; import p2.*; class PackageTest2 { public static void main(String str[]) { ClassA obA=new ClassA(); Classb obB=new ClassB(); obA.displayA(); obB.displayB(); } } DEPTT. OF COMP. SC & APPLICATIONS

  10. Default Package If a source file does not begin with the package statement, the classes contained in the source file reside in the default package The java compiler automatically looks in the default package to find classes. DEPTT. OF COMP. SC & APPLICATIONS

  11. CLASSPATH Environment Variable The compiler and runtime interpreter know how to find standard packages such as java.langand java.util The CLASSPATH environment variable is used to direct the compiler and interpreter to where programmer defined imported packages can be found The CLASSPATH environment variable is an ordered list of directories and files DEPTT. OF COMP. SC & APPLICATIONS

  12. CLASSPATH Environment Variable To set the CLASSPATH variable we use the following command: set CLASSPATH=c:\ Java compiler and interpreter searches the user defined packages from the above directory. To clear the previous setting we use: set CLASSPATH= DEPTT. OF COMP. SC & APPLICATIONS

  13. Adding a Class to a Package 1.Decide the name of the package. 2.Create the subdirectory with this name under the directory where the main source file is located. 3.Create classes to be placed in the package in separate source files and declare the package statement package packagename; 4. Compile each source file. When completed the package will contain .class files of the source files. DEPTT. OF COMP. SC & APPLICATIONS

  14. public/package/private scope Scope is concerned with the visibility of program elements such as classes and members Class members (methods or instance fields) can be defined with public, package (default), private or protected scope A class has two levels of visibility: -public scope means it is visible outside its containing package - default scope means it is visible only inside the package. (package scope/ friendly scope) DEPTT. OF COMP. SC & APPLICATIONS

  15. public/package/private scope conti.. • A class member with public scope means it is visible anywhere its class is visible • A class member with private scope means it is visible only within its encapsulating class • A class/class member with package scope means it is visible only inside its containing package • A class member with protected scope means it is visible every where except the non-subclasses in other package. DEPTT. OF COMP. SC & APPLICATIONS

  16. Levels of Access Control DEPTT. OF COMP. SC & APPLICATIONS

  17. MULTIPLE INHERITANCE :INTERFACES • An interface is a bit like a class, except you can only declare methods and variables in the interface • Interface define only abstract methods and final fields • Interfaces do not specify any code to implement methods. • Interfaces fields only contains constants. The general syntax is interface InterFaceName { variable declaration; method declaration; } DEPTT. OF COMP. SC & APPLICATIONS

  18. INTERFACE IMPLEMENTATION Interfaces are used as superclasses whose properties are inherited by classes. The general syntax is : class Classname implements InterFaceName { Body of ClassName } DEPTT. OF COMP. SC & APPLICATIONS

  19. INTERFACE EXAMPLE interface Area { final static float pi=3.14f; float compute (float x, float y); } class rectangle implements Area { public float compute (float x, float y) { return x*y; } } class InterfaceTest { public static void main(String arg[]) { Rectangle rect= new Rectangle(); Area area; area=rect; System.out.println("Area of Rectangle:="+area.compute(10,20)); } } DEPTT. OF COMP. SC & APPLICATIONS

  20. Exception Handling in Java Topics: –Introduction –Errors and Error handling –Exceptions –Types of Exceptions –Coding Exceptions –Summary DEPTT. OF COMP. SC & APPLICATIONS

  21. Introduction Users have high expectations for the code we produce. Users will use our programs in unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected ways during execution DEPTT. OF COMP. SC & APPLICATIONS

  22. Errors and Error Handling • An Error is any unexpected result obtained from a program during execution. • Unhandled errors may manifest themselves as incorrect results or behavior, or as abnormal program termination. • Errors should be handled by the programmer, to prevent them from reaching the user. DEPTT. OF COMP. SC & APPLICATIONS

  23. Errors and Error Handling Some typical causes of errors: –Memory errors (i.e. memory incorrectly allocated, memory leaks, “null pointer”) –File system errors (i.e. disk is full, disk has been removed) –Network errors (i.e. network is down, URL does not exist) –Calculation errors (i.e. divide by 0) DEPTT. OF COMP. SC & APPLICATIONS

  24. Errors and Error Handling More typical causes of errors: –Array errors (i.e. accessing element –1) –Conversion errors (i.e. convert ‘q’ to a number) –Can you think of some others? DEPTT. OF COMP. SC & APPLICATIONS

  25. Errors and Error Handling Traditional Error Handling Every method returns a value (flag) indicating either success, failure, or some error condition. The calling method checks the return flag and takes appropriate action. Downside: programmer must remember to always check the return value and take appropriate action. This requires much code (methods are harder to read) and something may get overlooked. DEPTT. OF COMP. SC & APPLICATIONS

  26. Exceptions What are they? –An exception is a representation of an error condition or a situation that is not the expected result of a method. –Exceptions are built into the Java language and are available to all program code. –Exceptions isolate the code that deals with the error condition from regular program logic. DEPTT. OF COMP. SC & APPLICATIONS

  27. Exceptions conti.. How are they used? –Exceptions fall into two categories: Checked Exceptions Unchecked Exceptions Checked exceptions are inherited from the core Java class Exception. They represent exceptions that are frequently considered “non fatal” to program execution Checked exceptions must be handled in your code, or passed to parent classes for handling. DEPTT. OF COMP. SC & APPLICATIONS

  28. Exceptions conti.. How are they used? • Unchecked exceptions represent error conditions that are considered “fatal” to program execution. • You do not have to do anything with an unchecked exception. Your program will terminate with an appropriate error message. DEPTT. OF COMP. SC & APPLICATIONS

  29. Exceptions conti… Examples: Checked exceptions include errors such as “array index out of bounds”, “file not found” and “number format conversion”. Unchecked exceptions include errors such as “null pointer”. DEPTT. OF COMP. SC & APPLICATIONS

  30. Exceptions conti... How do you handle exceptions? • Exception handling is accomplished through the “try – catch” mechanism, or by a “throws” clause in the method declaration. • –For any code that throws a checked exception, you can decide to handle the exception yourself, or pass the exception “up the chain” (to a parent class). DEPTT. OF COMP. SC & APPLICATIONS

  31. Try-Catch Mechanism Wherever your code may trigger an exception, the normal code logic is placed inside a block of code starting with the “try” keyword: After the try block, the code to handle the exception should it arise is placed in a block of code starting with the “catch” keyword. DEPTT. OF COMP. SC & APPLICATIONS

  32. Try-Catch Mechanism continues You may also write an optional “finally” block. This block contains code that is ALWAYS executed, either after the “try” block code, or after the “catch” block code. Finally blocks can be used for operations that must happen no matter what (i.e. cleanup operations such as closing a file) DEPTT. OF COMP. SC & APPLICATIONS

  33. try ..catch syntax try { … normal program code } catch(Exception e) { … exception handling code } DEPTT. OF COMP. SC & APPLICATIONS

  34. Coding Exceptions Passing the exception In any method that might throw an exception, you may declare the method as “throws” that exception, and thus avoid handling the exception yourself Example public void myMethod throws IOException { … normal code with some I/O } DEPTT. OF COMP. SC & APPLICATIONS

  35. Exception class All checked exceptions have class “Exception” as the parent class. You can use the actual exception class or the parent class when referring to an exception Where do you find the exception classes? DEPTT. OF COMP. SC & APPLICATIONS

  36. Coding Exceptions Example Types of Exceptions Examples: public void myMethod throws Exception { public void myMethod throws IOException { try { … } catch (Exception e) { … } try { … } catch (IOException ioe) { … } DEPTT. OF COMP. SC & APPLICATIONS

  37. import java.io.*; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; System.out.println("Access element three :" + a[3]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown:" + e); } • Code Example : OUTPUT Exception thrown :java.lang.ArrayIndexOutOfBoundsException: DEPTT. OF COMP. SC & APPLICATIONS

  38. Multiple catch Blocks: try { //Protected code } catch(ExceptionType1 e1) { //Catch block } catch(ExceptionType2 e2) { //Catch block } catch(ExceptionType3 e3) { //Catch block } DEPTT. OF COMP. SC & APPLICATIONS

  39. The finally Keyword try { //Protected code } catch(ExceptionType1 e1) { //Catch block } catch(ExceptionType2 e2) { //Catch block } catch(ExceptionType3 e3) { //Catch block } finally { //The finally block always executes. } DEPTT. OF COMP. SC & APPLICATIONS

  40. Declaring you own Exception: You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes: • All exceptions must be a child of Throwable. • If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. DEPTT. OF COMP. SC & APPLICATIONS

  41. Example //throwing your own exception import java.lang.Exception; class MyException extends Exception { MyException(String message) { super(message); } } class TestMyException { public static void main(String s[]) { int x=5,y=1000; try { float z=(float)x/(float)y; if(z<0.01) { throw new MyException("number is too small"); } } catch(MyException e) { System.out.println("Caught my exception"); System.out.println(e.getMessage()); } DEPTT. OF COMP. SC & APPLICATIONS

  42. OUTPUT • Caught my exception • •number is too small • •I am always here DEPTT. OF COMP. SC & APPLICATIONS

  43. Summary • Exceptions are a powerful error handling mechanism. • Exceptions in Java are built into the language. • Exceptions can be handled by the programmer (try-catch), or handled by the Java environment (throws). DEPTT. OF COMP. SC & APPLICATIONS

  44. REFERENCES • COMPLETE REFERENCE JAVA • JAVA 2 BY BALAGURUSWAMY • www.roseindia.net/java • www.wikipedia.org • http://www.java-examples.com • http://docs.oracle.com/javase • http://tutorials.jenkov.com • Beginning JAVA, Ivor Horton, WROX Public. DEPTT. OF COMP. SC & APPLICATIONS

More Related