SlideShare a Scribd company logo
Java Programming Language
Objectives


                In this session, you will learn to:
                   Create final classes, methods, and variables
                   Create and use enumerated types
                   Use the static import statement
                   Create abstract classes and methods
                   Create and use an interface
                   Define exceptions
                   Use try, catch, and finally statements
                   Describe exception categories
                   Identify common exceptions
                   Develop programs to handle your own exceptions
                   Use assertions
                   Distinguish appropriate and inappropriate uses of assertions
                   Enable assertions at runtime

     Ver. 1.0                        Session 7                            Slide 1 of 24
Java Programming Language
The final Keyword


                The final keyword is used for security reasons.
                It is used to create classes that serve as a standard.
                It implements the following restrictions:
                 –   You cannot subclass a final class.
                 –   You cannot override a final method.
                 –   A final variable is a constant.
                 –   All methods and data members in a final class are implicitly
                     final.
                You can set a final variable once only, but that
                assignment can occur independently of the declaration;
                this is called a blank final variable.




     Ver. 1.0                         Session 7                           Slide 2 of 24
Java Programming Language
Blank Final Variables


                A final variable that is not initialized in its declaration; its
                initialization is delayed:
                   A blank final instance variable must be assigned in a
                   constructor.
                   A blank final local variable can be set at any time in the body of
                   the method.
                It can be set once only.




     Ver. 1.0                        Session 7                              Slide 3 of 24
Java Programming Language
Enumerated Types


               • An enum type field consist of a fixed set of constants.
               • You can define an enum type by using the enum keyword.
                 For example, you would specify a days-of-the-week enum
                 type as:
                  public enum Day { SUNDAY, MONDAY, TUESDAY,
                  WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
               • The enum class body can include methods and other fields.
               • The compiler automatically adds some special methods
                 when it creates an enum.
               • All enums implicitly extend from java.lang.Enum. Since
                 Java does not support multiple inheritance, an enum cannot
                 extend anything else.



    Ver. 1.0                        Session 7                       Slide 4 of 24
Java Programming Language
Static Imports


                Imports the static members from a class:
                 import static
                 <pkg_list>.<class_name>.<member_name>;
                OR
                 import static <pkg_list>.<class_name>.*;
                Imports members individually or collectively:
                 import static cards.domain.Suit.SPADES;
                OR
                 import static cards.domain.Suit.*;
                There is no need to qualify the static constants:
                 PlayingCard card1 = new PlayingCard(SPADES,
                 2);


     Ver. 1.0                   Session 7                  Slide 5 of 24
Java Programming Language
Abstract Classes


                • An abstract class is declared with abstract access
                  specifier and it may or may not include abstract methods.
                • Abstract classes cannot be instantiated, but they can be
                  subclassed. For example:



                                                  Shape




                       Circle                Rectangle          Hexagon




     Ver. 1.0                         Session 7                       Slide 6 of 24
Java Programming Language
Abstract Classes (Contd.)


                An abstract class defines the common properties and
                behaviors of other classes.
                It is used as a base class to derive specific classes of the
                same type. For example:
                  abstract class Shape
                  {
                  public abstract float calculateArea();
                  }

                The preceding abstract method, calculateArea, is inherited
                by the subclasses of the Shape class. The subclasses
                Rectangle, Circle, and Hexagon implement this method in
                different ways.


     Ver. 1.0                       Session 7                          Slide 7 of 24
Java Programming Language
Abstract Classes (Contd.)


                A simple example of implementation of Abstract Method:
                 public class Circle extends Shape
                 {
                      float radius;
                      public float calculateArea()
                      {
                      return ((radius * radius)* (22/7));
                      }
                 }
                In the preceding example, the calculateArea() method has
                been overridden in the Circle class.



     Ver. 1.0                      Session 7                       Slide 8 of 24
Java Programming Language
Interfaces


                A public interface is a contract between client code and the
                class that implements that interface.
                A Java interface is a formal declaration of such a contract in
                which all methods contain no implementation.
                Many unrelated classes can implement the same interface.
                A class can implement many unrelated interfaces.
                Syntax of a Java class declaration with interface
                implementation is as follows:
                 <modifier> class <name> [extends
                 <superclass>]
                 [implements <interface> [,<interface>]* ]
                 { <member_declaration>*
                 }

     Ver. 1.0                       Session 7                          Slide 9 of 24
Java Programming Language
Interfaces (Contd.)


                Interfaces are used to define a behavior protocol (standard
                behavior) that can be implemented by any class anywhere
                in the class hierarchy. For example:
                Consider the devices TV and VDU. Both of them require a
                common functionality as far as brightness control is
                concerned. This functionality can be provided by
                implementing an interface called BrightnessControl which is
                applicable for both the devices.
                Interfaces can be implemented by classes that are not
                related to one another.
                Abstract classes are used only when there is a kind-of
                relationship between the classes.




     Ver. 1.0                      Session 7                        Slide 10 of 24
Java Programming Language
Interfaces (Contd.)


                Uses of Interfaces:
                   Declaring methods that one or more classes are expected to
                   implement
                   Determining an object’s programming interface without
                   revealing the actual body of the class
                   Capturing similarities between unrelated classes without
                   forcing a class relationship
                   Simulating multiple inheritance by declaring a class that
                   implements several interfaces




     Ver. 1.0                         Session 7                        Slide 11 of 24
Java Programming Language
Exceptions and Assertions


                Exceptions are a mechanism used to describe what to do
                when something unexpected happens. For example:
                   When a method is invoked with unacceptable arguments
                   A network connection fails
                   The user asks to open a non-existent file
                Assertions are a way to test certain assumptions about the
                logic of a program. For example:
                   To test that the value of a variable at a particular point is
                   always positive




     Ver. 1.0                         Session 7                               Slide 12 of 24
Java Programming Language
Exceptions


                Conditions that can readily occur in a correct program are
                checked exceptions.
                 – These are represented by the Exception class.
                Severe problems that normally are treated as fatal or
                situations that probably reflect program bugs are unchecked
                exceptions.
                 – Fatal situations are represented by the Error class.
                Probable bugs are represented by the RuntimeException
                class.
                The API documentation shows checked exceptions that can
                be thrown from a method.




     Ver. 1.0                        Session 7                            Slide 13 of 24
Java Programming Language
Exceptions (Contd.)


                  Consider the following code snippet:
                   public void myMethod(int num1 , int num2)
                   {
                      int result;
                      result = num2 / num1;
                      System.out.println(“Result:” + result);
                   }
                • In the preceding piece of code an exception
                  java.lang.ArithmeticException is thrown when the
                  value of num1 is equal to zero. The error message
                  displayed is:
                  Exception in thread “main”
                  java.lang.ArithmeticException: / by zero at
                  <classname>.main(<filename>)


     Ver. 1.0                     Session 7                   Slide 14 of 24
Java Programming Language
The try-catch Statement


                The try-catch block:
                 – The try block governs the statements that are enclosed within
                   it and defines the scope of the exception-handlers associated
                   with it.
                 – A try block must have at least one catch block that follows it
                   immediately.
                 – The catch statement takes the object of the exception class
                   that refers to the exception caught, as a parameter.
                 – Once the exception is caught, the statements within the catch
                   block are executed.
                 – The scope of the catch block is restricted to the statements in
                   the preceding try block only.




     Ver. 1.0                        Session 7                           Slide 15 of 24
Java Programming Language
The try-catch Statement (Contd.)


                An example of try-catch block:
                 public void myMethod(int num1 , int num2)
                 {
                   int result;
                   try{
                     result = num2 / num1;
                   }
                   catch(ArithmeticException e)
                   {
                     System.out.println(“Error…division by
                     zero”);
                   }
                   System.out.println(“Result:” + result);
                 }



     Ver. 1.0                 Session 7                Slide 16 of 24
Java Programming Language
Call Stack Mechanism


                If an exception is not handled in the current try-catch block,
                it is thrown to the caller of the method.
                If the exception gets back to the main method and is not
                handled there, the program is terminated abnormally.




     Ver. 1.0                       Session 7                          Slide 17 of 24
Java Programming Language
The finally Clause


                • The characteristics of the finally clause:
                   – Defines a block of code that always executes, regardless of
                     whether an exception is thrown.
                   – The finally block follows the catch blocks.
                   – It is not mandatory to have a finally block.




     Ver. 1.0                          Session 7                           Slide 18 of 24
Java Programming Language
Creating Your Own Exceptions


                Characteristics of user-defined exceptions:
                 – Created by extending the Exception class.
                 – The extended class contains constructors, data members and
                   methods.
                 – The throw and throws keywords are used while
                   implementing user-defined exceptions.




     Ver. 1.0                       Session 7                         Slide 19 of 24
Java Programming Language
Demonstration


               Let see how to create a custom Exception class, and use it in a
               Java program.




    Ver. 1.0                         Session 7                        Slide 20 of 24
Java Programming Language
Assertions


                  Syntax of an assertion is:
                    assert <boolean_expression> ;
                    assert <boolean_expression> :
                    <detail_expression> ;
                • If <boolean_expression> evaluates false, then an
                  AssertionError is thrown.
                • The second argument is converted to a string and used as
                  descriptive text in the AssertionError message.




     Ver. 1.0                        Session 7                      Slide 21 of 24
Java Programming Language
Assertions (Contd.)


                Recommended Uses of Assertions:
                   Use assertions to document and verify the assumptions and
                   internal logic of a single method:
                       Internal invariants
                       Control flow invariants
                       Postconditions and class invariants
                Inappropriate Uses of Assertions:
                   Do not use assertions to check the parameters of a public
                   method.
                   Do not use methods in the assertion check that can cause
                   side-effects.




     Ver. 1.0                         Session 7                         Slide 22 of 24
Java Programming Language
Summary


               In this session, you learned that:
                – final classes cannot be subclassed,final methods cannot
                  be overriden, and final variables are constant.
                – An enum type is a type whose fields consist of a fixed set of
                  constants.
                – An abstract class defines the common properties and
                  behaviors of other classes. It is used as a base class to derive
                  specific classes of the same type:
                    • Abstract classes allow implementation of a behavior in different
                      ways. The implementation is done in subclasses.
                    • An abstract class cannot be instantiated.
                    • Subclasses must override the abstract methods of the super class.
                – Interfaces are used to define a behavior protocol that can be
                  implemented by any class anywhere in the class hierarchy.



    Ver. 1.0                         Session 7                               Slide 23 of 24
Java Programming Language
Summary (Contd.)


               An exception is an abnormal event that occurs during the
               program execution and disrupts the normal flow of instructions.
               You can implement exception handling in your program by
               using the following keywords:
                •   try
                •   catch
                •   throws/throw
                •   finally
               Assertions can be used to document and verify the
               assumptions and internal logic of a single method:
                    Internal invariants
                    Control flow invariants
                    Postconditions and class invariants




    Ver. 1.0                       Session 7                         Slide 24 of 24

More Related Content

DOCX
DOCX
Core java questions
DOCX
Java Core
PDF
20 most important java programming interview questions
DOC
Core java interview questions
PPT
Top 10 Interview Questions For Java
PDF
Core Java Introduction | Basics
Core java questions
Java Core
20 most important java programming interview questions
Core java interview questions
Top 10 Interview Questions For Java
Core Java Introduction | Basics

What's hot (20)

DOCX
Basic java important interview questions and answers to secure a job
PDF
Java/J2EE interview Qestions
PPTX
Java interview questions 2
DOC
Complete java&j2ee
DOCX
Java questions for viva
DOCX
Corejavainterviewquestions.doc
PDF
Java scjp-part1
PDF
java-06inheritance
PPTX
Object+oriented+programming+in+java
PDF
Core Java Certification
PDF
Java Presentation For Syntax
PDF
JAVA Object Oriented Programming (OOP)
PPT
Interfaces In Java
DOC
Questions of java
PDF
OOPs difference faqs-3
DOC
Java interview questions
PDF
37 Java Interview Questions
PPS
Dacj 2-1 c
PDF
Java interview question
PDF
[JWPA-1]의존성 주입(Dependency injection)
Basic java important interview questions and answers to secure a job
Java/J2EE interview Qestions
Java interview questions 2
Complete java&j2ee
Java questions for viva
Corejavainterviewquestions.doc
Java scjp-part1
java-06inheritance
Object+oriented+programming+in+java
Core Java Certification
Java Presentation For Syntax
JAVA Object Oriented Programming (OOP)
Interfaces In Java
Questions of java
OOPs difference faqs-3
Java interview questions
37 Java Interview Questions
Dacj 2-1 c
Java interview question
[JWPA-1]의존성 주입(Dependency injection)

Viewers also liked (20)

PPS
15 ooad uml-20
PPS
Vb.net session 09
PPS
Dacj 2-2 c
PPS
Oops recap
PPS
11 ds and algorithm session_16
PPS
09 iec t1_s1_oo_ps_session_13
PDF
OOP Java
PPS
Rdbms xp 01
PPS
Jdbc session01
PPS
14 ooad uml-19
PPS
Deawsj 7 ppt-2_c
PDF
Java Garbage Collection - How it works
PPS
Ds 8
PDF
Understanding Java Garbage Collection - And What You Can Do About It
PPS
Aae oop xp_06
PPS
Dacj 1-1 a
PDF
Chapter 21 c language
PPS
Ajs 4 a
PPTX
Introduction to programming
PPS
Dacj 1-1 b
15 ooad uml-20
Vb.net session 09
Dacj 2-2 c
Oops recap
11 ds and algorithm session_16
09 iec t1_s1_oo_ps_session_13
OOP Java
Rdbms xp 01
Jdbc session01
14 ooad uml-19
Deawsj 7 ppt-2_c
Java Garbage Collection - How it works
Ds 8
Understanding Java Garbage Collection - And What You Can Do About It
Aae oop xp_06
Dacj 1-1 a
Chapter 21 c language
Ajs 4 a
Introduction to programming
Dacj 1-1 b

Similar to (20)

PPS
Java session02
PPT
Ap Power Point Chpt5
PPT
core java
PDF
Exception handling and packages.pdf
PPS
Dacj 1-2 b
PPS
Java session05
PDF
Java concepts and questions
PPT
Core java
PPTX
14.jun.2012
PPT
9 abstract interface
PPT
Core java by a introduction sandesh sharma
PDF
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
PPS
Java session01
TXT
Java interview
PPTX
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
PDF
javainterface
PPTX
PPT
Lecture 2 classes i
PPTX
UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
PPTX
Android webinar class_java_review
Java session02
Ap Power Point Chpt5
core java
Exception handling and packages.pdf
Dacj 1-2 b
Java session05
Java concepts and questions
Core java
14.jun.2012
9 abstract interface
Core java by a introduction sandesh sharma
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
Java session01
Java interview
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
javainterface
Lecture 2 classes i
UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
Android webinar class_java_review

More from Niit Care (20)

PPS
Ajs 1 b
PPS
Ajs 4 b
PPS
Ajs 4 c
PPS
Ajs 3 b
PPS
Ajs 3 a
PPS
Ajs 3 c
PPS
Ajs 2 b
PPS
Ajs 2 a
PPS
Ajs 2 c
PPS
Ajs 1 a
PPS
Ajs 1 c
PPS
Dacj 4 2-c
PPS
Dacj 4 2-b
PPS
Dacj 4 2-a
PPS
Dacj 4 1-c
PPS
Dacj 4 1-b
PPS
Dacj 4 1-a
PPS
Dacj 1-3 c
PPS
Dacj 1-3 b
PPS
Dacj 1-3 a
Ajs 1 b
Ajs 4 b
Ajs 4 c
Ajs 3 b
Ajs 3 a
Ajs 3 c
Ajs 2 b
Ajs 2 a
Ajs 2 c
Ajs 1 a
Ajs 1 c
Dacj 4 2-c
Dacj 4 2-b
Dacj 4 2-a
Dacj 4 1-c
Dacj 4 1-b
Dacj 4 1-a
Dacj 1-3 c
Dacj 1-3 b
Dacj 1-3 a

Recently uploaded (20)

PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
A Presentation on Artificial Intelligence
PDF
Empathic Computing: Creating Shared Understanding
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Spectroscopy.pptx food analysis technology
PPTX
Cloud computing and distributed systems.
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPT
Teaching material agriculture food technology
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Approach and Philosophy of On baking technology
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Advanced methodologies resolving dimensionality complications for autism neur...
Programs and apps: productivity, graphics, security and other tools
Network Security Unit 5.pdf for BCA BBA.
MIND Revenue Release Quarter 2 2025 Press Release
Encapsulation_ Review paper, used for researhc scholars
Review of recent advances in non-invasive hemoglobin estimation
A Presentation on Artificial Intelligence
Empathic Computing: Creating Shared Understanding
The AUB Centre for AI in Media Proposal.docx
Spectroscopy.pptx food analysis technology
Cloud computing and distributed systems.
Reach Out and Touch Someone: Haptics and Empathic Computing
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
Electronic commerce courselecture one. Pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Teaching material agriculture food technology
Per capita expenditure prediction using model stacking based on satellite ima...
Approach and Philosophy of On baking technology

  • 1. Java Programming Language Objectives In this session, you will learn to: Create final classes, methods, and variables Create and use enumerated types Use the static import statement Create abstract classes and methods Create and use an interface Define exceptions Use try, catch, and finally statements Describe exception categories Identify common exceptions Develop programs to handle your own exceptions Use assertions Distinguish appropriate and inappropriate uses of assertions Enable assertions at runtime Ver. 1.0 Session 7 Slide 1 of 24
  • 2. Java Programming Language The final Keyword The final keyword is used for security reasons. It is used to create classes that serve as a standard. It implements the following restrictions: – You cannot subclass a final class. – You cannot override a final method. – A final variable is a constant. – All methods and data members in a final class are implicitly final. You can set a final variable once only, but that assignment can occur independently of the declaration; this is called a blank final variable. Ver. 1.0 Session 7 Slide 2 of 24
  • 3. Java Programming Language Blank Final Variables A final variable that is not initialized in its declaration; its initialization is delayed: A blank final instance variable must be assigned in a constructor. A blank final local variable can be set at any time in the body of the method. It can be set once only. Ver. 1.0 Session 7 Slide 3 of 24
  • 4. Java Programming Language Enumerated Types • An enum type field consist of a fixed set of constants. • You can define an enum type by using the enum keyword. For example, you would specify a days-of-the-week enum type as: public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } • The enum class body can include methods and other fields. • The compiler automatically adds some special methods when it creates an enum. • All enums implicitly extend from java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else. Ver. 1.0 Session 7 Slide 4 of 24
  • 5. Java Programming Language Static Imports Imports the static members from a class: import static <pkg_list>.<class_name>.<member_name>; OR import static <pkg_list>.<class_name>.*; Imports members individually or collectively: import static cards.domain.Suit.SPADES; OR import static cards.domain.Suit.*; There is no need to qualify the static constants: PlayingCard card1 = new PlayingCard(SPADES, 2); Ver. 1.0 Session 7 Slide 5 of 24
  • 6. Java Programming Language Abstract Classes • An abstract class is declared with abstract access specifier and it may or may not include abstract methods. • Abstract classes cannot be instantiated, but they can be subclassed. For example: Shape Circle Rectangle Hexagon Ver. 1.0 Session 7 Slide 6 of 24
  • 7. Java Programming Language Abstract Classes (Contd.) An abstract class defines the common properties and behaviors of other classes. It is used as a base class to derive specific classes of the same type. For example: abstract class Shape { public abstract float calculateArea(); } The preceding abstract method, calculateArea, is inherited by the subclasses of the Shape class. The subclasses Rectangle, Circle, and Hexagon implement this method in different ways. Ver. 1.0 Session 7 Slide 7 of 24
  • 8. Java Programming Language Abstract Classes (Contd.) A simple example of implementation of Abstract Method: public class Circle extends Shape { float radius; public float calculateArea() { return ((radius * radius)* (22/7)); } } In the preceding example, the calculateArea() method has been overridden in the Circle class. Ver. 1.0 Session 7 Slide 8 of 24
  • 9. Java Programming Language Interfaces A public interface is a contract between client code and the class that implements that interface. A Java interface is a formal declaration of such a contract in which all methods contain no implementation. Many unrelated classes can implement the same interface. A class can implement many unrelated interfaces. Syntax of a Java class declaration with interface implementation is as follows: <modifier> class <name> [extends <superclass>] [implements <interface> [,<interface>]* ] { <member_declaration>* } Ver. 1.0 Session 7 Slide 9 of 24
  • 10. Java Programming Language Interfaces (Contd.) Interfaces are used to define a behavior protocol (standard behavior) that can be implemented by any class anywhere in the class hierarchy. For example: Consider the devices TV and VDU. Both of them require a common functionality as far as brightness control is concerned. This functionality can be provided by implementing an interface called BrightnessControl which is applicable for both the devices. Interfaces can be implemented by classes that are not related to one another. Abstract classes are used only when there is a kind-of relationship between the classes. Ver. 1.0 Session 7 Slide 10 of 24
  • 11. Java Programming Language Interfaces (Contd.) Uses of Interfaces: Declaring methods that one or more classes are expected to implement Determining an object’s programming interface without revealing the actual body of the class Capturing similarities between unrelated classes without forcing a class relationship Simulating multiple inheritance by declaring a class that implements several interfaces Ver. 1.0 Session 7 Slide 11 of 24
  • 12. Java Programming Language Exceptions and Assertions Exceptions are a mechanism used to describe what to do when something unexpected happens. For example: When a method is invoked with unacceptable arguments A network connection fails The user asks to open a non-existent file Assertions are a way to test certain assumptions about the logic of a program. For example: To test that the value of a variable at a particular point is always positive Ver. 1.0 Session 7 Slide 12 of 24
  • 13. Java Programming Language Exceptions Conditions that can readily occur in a correct program are checked exceptions. – These are represented by the Exception class. Severe problems that normally are treated as fatal or situations that probably reflect program bugs are unchecked exceptions. – Fatal situations are represented by the Error class. Probable bugs are represented by the RuntimeException class. The API documentation shows checked exceptions that can be thrown from a method. Ver. 1.0 Session 7 Slide 13 of 24
  • 14. Java Programming Language Exceptions (Contd.) Consider the following code snippet: public void myMethod(int num1 , int num2) { int result; result = num2 / num1; System.out.println(“Result:” + result); } • In the preceding piece of code an exception java.lang.ArithmeticException is thrown when the value of num1 is equal to zero. The error message displayed is: Exception in thread “main” java.lang.ArithmeticException: / by zero at <classname>.main(<filename>) Ver. 1.0 Session 7 Slide 14 of 24
  • 15. Java Programming Language The try-catch Statement The try-catch block: – The try block governs the statements that are enclosed within it and defines the scope of the exception-handlers associated with it. – A try block must have at least one catch block that follows it immediately. – The catch statement takes the object of the exception class that refers to the exception caught, as a parameter. – Once the exception is caught, the statements within the catch block are executed. – The scope of the catch block is restricted to the statements in the preceding try block only. Ver. 1.0 Session 7 Slide 15 of 24
  • 16. Java Programming Language The try-catch Statement (Contd.) An example of try-catch block: public void myMethod(int num1 , int num2) { int result; try{ result = num2 / num1; } catch(ArithmeticException e) { System.out.println(“Error…division by zero”); } System.out.println(“Result:” + result); } Ver. 1.0 Session 7 Slide 16 of 24
  • 17. Java Programming Language Call Stack Mechanism If an exception is not handled in the current try-catch block, it is thrown to the caller of the method. If the exception gets back to the main method and is not handled there, the program is terminated abnormally. Ver. 1.0 Session 7 Slide 17 of 24
  • 18. Java Programming Language The finally Clause • The characteristics of the finally clause: – Defines a block of code that always executes, regardless of whether an exception is thrown. – The finally block follows the catch blocks. – It is not mandatory to have a finally block. Ver. 1.0 Session 7 Slide 18 of 24
  • 19. Java Programming Language Creating Your Own Exceptions Characteristics of user-defined exceptions: – Created by extending the Exception class. – The extended class contains constructors, data members and methods. – The throw and throws keywords are used while implementing user-defined exceptions. Ver. 1.0 Session 7 Slide 19 of 24
  • 20. Java Programming Language Demonstration Let see how to create a custom Exception class, and use it in a Java program. Ver. 1.0 Session 7 Slide 20 of 24
  • 21. Java Programming Language Assertions Syntax of an assertion is: assert <boolean_expression> ; assert <boolean_expression> : <detail_expression> ; • If <boolean_expression> evaluates false, then an AssertionError is thrown. • The second argument is converted to a string and used as descriptive text in the AssertionError message. Ver. 1.0 Session 7 Slide 21 of 24
  • 22. Java Programming Language Assertions (Contd.) Recommended Uses of Assertions: Use assertions to document and verify the assumptions and internal logic of a single method: Internal invariants Control flow invariants Postconditions and class invariants Inappropriate Uses of Assertions: Do not use assertions to check the parameters of a public method. Do not use methods in the assertion check that can cause side-effects. Ver. 1.0 Session 7 Slide 22 of 24
  • 23. Java Programming Language Summary In this session, you learned that: – final classes cannot be subclassed,final methods cannot be overriden, and final variables are constant. – An enum type is a type whose fields consist of a fixed set of constants. – An abstract class defines the common properties and behaviors of other classes. It is used as a base class to derive specific classes of the same type: • Abstract classes allow implementation of a behavior in different ways. The implementation is done in subclasses. • An abstract class cannot be instantiated. • Subclasses must override the abstract methods of the super class. – Interfaces are used to define a behavior protocol that can be implemented by any class anywhere in the class hierarchy. Ver. 1.0 Session 7 Slide 23 of 24
  • 24. Java Programming Language Summary (Contd.) An exception is an abnormal event that occurs during the program execution and disrupts the normal flow of instructions. You can implement exception handling in your program by using the following keywords: • try • catch • throws/throw • finally Assertions can be used to document and verify the assumptions and internal logic of a single method: Internal invariants Control flow invariants Postconditions and class invariants Ver. 1.0 Session 7 Slide 24 of 24