The InterruptedException is thrown when a thread that is working or sleeping is interrupted. Throwing/catching this exception allows your code to know if and when a thread has been stopped. 4. NoSuchMethodException Like the InvocationTargetException (above), the NoSuchMethodException is related to the use of reflection. This error stems from trying to access a provided method name that either does not exist or is configured as a private method. Consider the simple example below: public class Example { public int divide(int numerator) { return numerator / 0; } public int addOne(int number) { return doSomethingPrivate(number); } private int doSomethingPrivate(int number) { return number++; } } The doSomethingPrivate() method is a private method and not visible in the following scenario: Class c = Class.forName(\"Example\"); Method = c.getDeclaredMethod(\"doSomethingPrivate\", parameterTypes); method.invoke(objectToInvokeOn, params); As a result, it throws a NoSuchMethodException. Unchecked Exceptions Now let's look at some of the most common Unchecked exceptions in Java. 1. NullPointerException A NullPointerException is thrown when a Java program attempts to process an object which contains a null value. public class Example { public void doSomething() { CU IDOL SELF LEARNING MATERIAL (SLM) 201
Integer number = null; if (number > 0) { System.out.println(\"Positive number\"); } } } In the example above, the number (Integer) object is null, so performing a simple evaluation will throw a NullPointerException. 2. ArrayIndexOutOfBoundsException The ArrayIndexOutOfBoundsException occurs while processing an array and asking for a position that does not exist within the size of the array. Consider the following example: public class Example { public void processArray() { List names = new ArrayList<>(); names.add(\"Eric\"); names.add(\"Sydney\"); return names.get(5); } } The names list contains two values, so 1 is the valid max index of this zero-based structure. As a result, asking for the name at position 5 will return an ArrayIndexOutOfBoundsException. 3. IllegalStateException The IllegalStateException is thrown when a method is being called at an illegal or inappropriate time. A common occurrence of this exception is thrown when attempting to remove an item from the list while you are processing that list, as demonstrated below: public class Example { public void processArray() { List names = new ArrayList<>(); names.add(\"Eric\"); names.add(\"Sydney\"); CU IDOL SELF LEARNING MATERIAL (SLM) 202
Iterator iterator = names.iterator(); while (iterator.hasNext()) { iterator.remove(); } } } In the example above, calling the remove() method inside the while loop will throw an IllegalStateException. 4. ClassCastException The ClassCastException is thrown when you attempt to cast one object into another object that is not a member of the class hierarchy. This could be as simple as trying to cast a Long object to a String object as shown below: public class Example { public void incorrectCastExample() { Long value = 1967L; String name = (String) value; } } 5. ArithmeticException The ArithmeticException occurs when an exceptional arithmetic condition has occurred. For example, this type of exception often happens when a program attempts to divide by zero, which was first illustrated in the InvocationTargetException section (above): return numerator / 0; Dividing by zero is not a valid mathematical operation, which throws an ArithmeticException in Java. 6. IllegalArgumentException The IllegalArgumentException is often used to capture errors when a provided method value does not meet expectations. To illustrate, consider an example where a date is requested and cannot be in the future: public class Example { public void validDate(LocalDate localDate) throws IllegalArgumentException { CU IDOL SELF LEARNING MATERIAL (SLM) 203
if (localDate.after(LocalDate.now())) { throw IllegalArgumentException(\"localDate=\" + localDate + \" cannot be in the future\"); } } } While a future date is a valid value for the date-based object, the business rules for this instance requires the object to not be in the future. 7.3 HANDLING OF EXCEPTION A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed. Exceptions can be generated by the Java run-time system, or they can be manually generated by your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. Manually generated exceptions are typically used to report some error condition to the caller of a method. Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Briefly, here is how they work. Program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed before a method returns is put in a finally block. This is the general form of an exception-handling block: try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 CU IDOL SELF LEARNING MATERIAL (SLM) 204
} // ... finally { // block of code to be executed before try block ends } Here, ExceptionType is the type of exception that has occurred. 7.4 EXCEPTION TYPE All exception types are subclasses of the built-in class throw able. Thus, Throwableis at the top of the exception class hierarchy. Immediately below Throw able are two subclasses that partition exceptions into two distinct branches. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. This is also the class that you will subclass to create your own custom exception types. There is an important subclass of Exception, called Runtime Exception. Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing. The other branch is topped by Error, which defines exceptions that are not expected to be caught under normal circumstances by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Stack overflow is an example of such an error. 7.5 USING TRY-CATCH The try...catch block in Java is used to handle exceptions and prevents the abnormal termination of the program. Here's the syntax of a try...catch block in Java. try{ // code } catch(exception) { // code } The try block includes the code that might generate an exception. CU IDOL SELF LEARNING MATERIAL (SLM) 205
The catch block includes the code that is executed when there occurs an exception inside the try block. Example: Java try...catch block class Main { public static void main(String[] args) { try { int divideByZero = 5 / 0; System.out.println(\"Rest of code in try block\"); } catch (ArithmeticException e) { System.out.println(\"ArithmeticException => \" + e.getMessage()); } } } Output ArithmeticException => / by zero In the above example, notice the line, int divideByZero = 5 / 0; Here, we are trying to divide a number by zero. In this case, an exception occurs. Hence, we have enclosed this code inside the try block. When the program encounters this code, ArithmeticException occurs. And, the exception is caught by the catch block and executes the code inside the catch block. The catch block is only executed if there exists an exception inside the try block. Note: In Java, we can use a try block without a catch block. However, we cannot use a catch block without a try block. Java try...finally block We can also use the try block along with a finally block. In this case, the finally block is always executed whether there is an exception inside the try block or not. Example: Java try...finally block class Main { public static void main(String[] args) { CU IDOL SELF LEARNING MATERIAL (SLM) 206
try { int divideByZero = 5 / 0; } finally { System.out.println(\"Finally block is always executed\"); } } } Output Finally block is always executed Exception in thread \"main\" java.lang.ArithmeticException: / by zero at Main.main(Main.java:4) In the above example, we have used the try block along with the finally block. We can see that the code inside the try block is causing an exception. However, the code inside the finally block is executed irrespective of the exception. Java try...catch...finally block In Java, we can also use the finally block after the try...catch block. For example, import java.io.*; class ListOfNumbers { // create an integer array private int[] list = {5, 6, 8, 9, 2}; // method to write data from array to a fila public void writeList() { PrintWriter out = null; try { System.out.println(\"Entering try statement\"); // creating a new file OutputFile.txt out = new PrintWriter(new FileWriter(\"OutputFile.txt\")); // writing values from list array to Output.txt for (int i = 0; i < 7; i++) { CU IDOL SELF LEARNING MATERIAL (SLM) 207
out.println(\"Value at: \" + i + \" = \" + list[i]); } } catch (Exception e) { System.out.println(\"Exception => \" + e.getMessage()); } finally { // checking if PrintWriter has been opened if (out != null) { System.out.println(\"Closing PrintWriter\"); // close PrintWriter out.close(); } else { System.out.println(\"PrintWriter not open\"); } } } } class Main { public static void main(String[] args) { ListOfNumbers list = new ListOfNumbers(); list.writeList(); } } Output Entering try statement Exception => Index 5 out of bounds for length 5 Closing PrintWriter CU IDOL SELF LEARNING MATERIAL (SLM) 208
In the above example, we have created an array named list and a file named output.txt. Here, we are trying to read data from the array and storing to the file. Notice the code, for (int i = 0; i < 7; i++) { out.println(\"Value at: \" + i + \" = \" + list[i]); } Java try...catch In this tutorial, we will learn about the try catch statement in Java with the help of examples. The try...catch block in Java is used to handle exceptions and prevents the abnormal termination of the program. Here's the syntax of a try...catch block in Java. try{ // code } catch(exception) { // code } The try block includes the code that might generate an exception. The catch block includes the code that is executed when there occurs an exception inside the try block. Example: Java try...catch block class Main { public static void main(String[] args) { try { int divideByZero = 5 / 0; System.out.println(\"Rest of code in try block\"); } catch (ArithmeticException e) { System.out.println(\"ArithmeticException => \" + e.getMessage()); CU IDOL SELF LEARNING MATERIAL (SLM) 209
} } } Output ArithmeticException => / by zero In the above example, notice the line, int divideByZero = 5 / 0; Here, we are trying to divide a number by zero. In this case, an exception occurs. Hence, we have enclosed this code inside the try block. When the program encounters this code, ArithmeticException occurs. And, the exception is caught by the catch block and executes the code inside the catch block. The catch block is only executed if there exists an exception inside the try block. Note: In Java, we can use a try block without a catch block. However, we cannot use a catch block without a try block. Java try...finally block We can also use the try block along with a finally block. In this case, the finally block is always executed whether there is an exception inside the try block or not. Example: Java try...finally block class Main { public static void main(String[] args) { try { int divideByZero = 5 / 0; } finally { System.out.println(\"Finally block is always executed\"); } } } Output CU IDOL SELF LEARNING MATERIAL (SLM) 210
Finally block is always executed Exception in thread \"main\" java.lang.ArithmeticException: / by zero at Main.main(Main.java:4) In the above example, we have used the try block along with the finally block. We can see that the code inside the try block is causing an exception. However, the code inside the finally block is executed irrespective of the exception. Java try...catch...finally block In Java, we can also use the finally block after the try...catch block. For example, import java.io.*; class ListOfNumbers { // create an integer array private int[] list = {5, 6, 8, 9, 2}; // method to write data from array to a fila public void writeList() { PrintWriter out = null; try { System.out.println(\"Entering try statement\"); // creating a new file OutputFile.txt out = new PrintWriter(new FileWriter(\"OutputFile.txt\")); // writing values from list array to Output.txt for (int i = 0; i < 7; i++) { out.println(\"Value at: \" + i + \" = \" + list[i]); } } catch (Exception e) { System.out.println(\"Exception => \" + e.getMessage()); } finally { // checking if PrintWriter has been opened if (out != null) { CU IDOL SELF LEARNING MATERIAL (SLM) 211
System.out.println(\"Closing PrintWriter\"); // close PrintWriter out.close(); } else { System.out.println(\"PrintWriter not open\"); } } } } class Main { public static void main(String[] args) { ListOfNumbers list = new ListOfNumbers(); list.writeList(); } } Output Entering try statement Exception => Index 5 out of bounds for length 5 Closing PrintWriter In the above example, we have created an array named list and a file named output.txt. Here, we are trying to read data from the array and storing to the file. Notice the code, for (int i = 0; i < 7; i++) { out.println(\"Value at: \" + i + \" = \" + list[i]); } Here, the size of the array is 5 and the last element of the array is at list[4]. However, we are trying to access elements at a[5] and a[6]. Hence, the code generates an exception that is CU IDOL SELF LEARNING MATERIAL (SLM) 212
caught by the catch block. Since the finally block is always executed, we have included code to close the PrintWriter inside the finally block. It is a good practice to use finally blocks to include important cleanup code like closing a file or connection. Note: There are some cases when a finally block does not execute: Use of System.exit() method An exception occurs in the finally block The death of a thread Multiple Catch blocks For each try block, there can be zero or more catch blocks. Multiple catch blocks allow us to handle each exception differently. The argument type of each catch block indicates the type of exception that can be handled by it. For example, class ListOfNumbers { public int[] arr = new int[10]; public void writeList() { try { arr[10] = 11; } catch (NumberFormatException e1) { System.out.println(\"NumberFormatException => \" + e1.getMessage()); } catch (IndexOutOfBoundsException e2) { System.out.println(\"IndexOutOfBoundsException => \" + e2.getMessage()); } } } class Main { public static void main(String[] args) { ListOfNumbers list = new ListOfNumbers(); CU IDOL SELF LEARNING MATERIAL (SLM) 213
list.writeList(); } } Output IndexOutOfBoundsException => Index 10 out of bounds for length 10 In this example, we have created an integer array named arr of size 10. Since the array index starts from 0, the last element of the array is at arr[9]. Notice the statement, arr[10] = 11; Here, we are trying to assign a value to the index 10. Hence, IndexOutOfBoundException occurs. When an exception occurs in the try block, The exception is thrown to the first catch block. The first catch block does not handle an IndexOutOfBoundsException, so it is passed to the next catch block. The second catch block in the above example is the appropriate exception handler because it handles an IndexOutOfBoundsException. Hence, it is executed. 7.6 CATCHING MULTIPLE EXCEPTIONS From Java SE 7 and later, we can now catch more than one type of exception with one catch block.This reduces code duplication and increases code simplicity and efficiency.Each exception type that can be handled by the catch block is separated using a vertical bar |.Its syntax is: try { // code } catch (ExceptionType1 | Exceptiontype2 ex) { // catch block } 7.7 SUMMARY Exception handling is one of the most important features of java programming that allows us to handle the runtime errors caused by exceptions. CU IDOL SELF LEARNING MATERIAL (SLM) 214
A Java exception is an object that describes an exceptional condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. Exceptions can be generated by the Java run-time system, or they can be manually generated by your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. All exception types are subclasses of the built-in class Throw able. Thus, Throwableis at the top of the exception class hierarchy. Immediately below Throw able are two subclasses that partition exceptions into two distinct branches. Like most modern programming languages, Java includes the concept of exceptions to handle both errors and \"exceptional events.\" When an exception occurs in your code, it disrupts the normal instruction logic and abnormally terminates the process. 7.8 KEYWORDS Exception: An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system. This block of code is called an exception handler. Try catch: \"Try\" and \"catch\" are keywords that represent the handling of exceptions due to data or coding errors during program execution. A try block is the block of code in which exceptions occur. A catch block catches and handles try blocking exceptions. The finally block: The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occur or not. Index: An index can be defined on a Collection property (java. util. Collection implementation) or Array. Setting such an index means that each of the Collection's or Array's items is indexed. Setting an index on a Collection / Array done using the Space Index. Throw: The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions. CU IDOL SELF LEARNING MATERIAL (SLM) 215
7.9 LEARNING ACTIVITY 1. Conduct a seminar on exception. ________________________________________________________________________ __________________________________________________________________ 2. Discuss the topic using try catch. ________________________________________________________________________ __________________________________________________________________ 7.10 UNIT END QUESTIONS A. Descriptive Questions Short Questions: 1. What do you mean by an exception? 2. How would you explain a ClassCastException in Java? 3. Write syntax of a try catch block in Java? 4. What are some examples of unchecked exceptions? 5. Define OutOfMemoryError in Java. Long Questions: 1. What are the types of exceptions? Explain them. 2. What is the possibility of keeping other statements in between ‘try’, ‘catch’, and ‘finally’ blocks? 3. Explain how exceptions can be handled in Java. What is the exception handling mechanism behind the process? 4. Why do you use the ‘throws’ keyword in Java? 5. Differentiate between throw, throws and throw able in Java? B. Multiple Choice Questions 1. What are the types of exceptions in Java programming? a. Checked exception b. Unchecked exception c. Both A & B d. Multiple Extension CU IDOL SELF LEARNING MATERIAL (SLM) 216
2. When is the checked exception caught? a. Compile time b. Run time c. Both at compile and run time d. Doesn’t run 3. When does Unchecked exception caught at? a. Compile time b. Run time c. Both at compile and run time d. Doesn’t run time 4. Which is the super class of all java exceptions classes? a. Exception b. RuntimeException c. Throwable d. IOException 5. What are the un-checked(runtime) exception in java? a. ArrayIndexOutOfBoundsException b. ArithmeticException c. NullPointerException d. All of these Answers 1-c, 2-a, 3-b, 4-c, 5-d 7.11 REFERENCES References John Hauser (1996). \"Handling Floating-Point Exceptions in Numeric Programs,. Bloch, Joshua (2008). \"Item 57: Use exceptions only for exceptional situations\". Effective Java (Second edition). Lajoie, José (March–April 1994). \"Exception handling – Supporting the runtime mechanism\". C++ Report. CU IDOL SELF LEARNING MATERIAL (SLM) 217
Textbooks Bill Veneers; Bruce Eckel (August 18, 2003). \"The Trouble with Checked Exceptions: A Conversation with Anders Hejlsberg, Part II\". p. 2. Archived from the original on February 18, 2015. \"Unchecked Exceptions – The Controversy Goodenough, John B. (1975a). Structured exception handling. Proceedings of the 2nd ACM SIGACT-SIGPLAN Website https://www.mygreatlearning.com https://www.w3schools.com https://beginnersbook.com CU IDOL SELF LEARNING MATERIAL (SLM) 218
UNIT – 8:EXCEPTION HANDLING 2 STRUCTURE 8.0 Learning Objectives 8.1 Introduction 8.2 Using finally clause 8.3 Types of Exceptions 8.3.1 Built-in Exception 8.3.2 User-Defined Exception 8.4Throwing Exceptions 8.5 Writing Exception Subclasses 8.6 Summary 8.7 Keywords 8.8 Learning Activity 8.9 Unit End Questions 8.10 Reference 8.0 LEARNING OBJECTIVES After studying this unit, you will be able to: Illustrate using finally clause Describe types of Exceptions Explain throwing Exceptions and writing exception subclasses 8.1 INTRODUCTION An Exception is an abnormal condition that arises in the code sequence at run time. Java provides a mechanism to handle the Exception that occurs that run time so that you can have your code run smoothly instead of situations that might cause your code to break at run- time. A java exception is an object that describes an exceptional condition that has occurred in the piece of code. Java exception handling is managed via five keywords try, catch, throw, throws and finally. We will learn about the usage of each of these terms subsequently. CU IDOL SELF LEARNING MATERIAL (SLM) 219
As a general rule, the part of your code that might generate an Exception at run-time should be inside a try block and the catch condition should be inside a catch block. Following is the structure of exception handling block All Exception types in Java are of type Throw able. Thus Throw able is at the top of Exception hierarchy. Immediately below Throw able are two subclasses that partition exception into Exception and Errors. Errors are catastrophic failures which are usually not handled by our program. On the other hand Exceptions class is used for exceptional conditions that user program should catch. There is an important subclass of Exception i.e. Runtime Exceptions. Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing. Before we start looking at how to catch the Exceptions, Let’s look at why there is a need of Exception Handling. Let’s write a program which does not handle the exceptions. public class NoHandling { public static void main(String args[]) { int d = 0; int a = 232 / d; } } On running this program will generate the following stack trace. Exception in thread “main” java.lang.ArithmeticException: / by zero at info.FiveBalloons.Examples.NoHandling.main(NoHandling.java:7) The stacktrace will show the sequence of method invocation that led up to the error. This is the default exception handling provided by the Java run-time system. But you will want to handle the exceptions yourself. Doing so provides two benefits. It allows you to fix the error. It prevents the program from automatically terminating. Let’s fix the above piece of code using Java Exception Handling. public class NoHandling { public static void main(String args[]) { int d, a; try { CU IDOL SELF LEARNING MATERIAL (SLM) 220
d = 0; a = 232 / d; } catch (ArithmeticException e) { // Catch divide-by-zero Errors a = 0; System.out.println(\"Division by Zero, setting value of a as 0\"); } } } As you can see in the catch block we have adjusted the value of a, as well as handled the exception so that the code does not terminate at the exception. 8.2 USING FINALLY CLAUSE The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occur or not. There are 3 possible cases where finally block can be used: Case 1: When an exception does not rise In this case, the program runs fine without throwing any exception and finally block execute after the try block. // Java program to demonstrate // finally block in java When // exception does not rise import java.io.*; class GFG { public static void main(String[] args) { try { System.out.println(\"inside try block\"); // Not throw any exception CU IDOL SELF LEARNING MATERIAL (SLM) 221
System.out.println(34 / 2); } // Not execute in this case catch (ArithmeticException e) { System.out.println(\"Arithmetic Exception\"); } // Always execute finally { System.out.println( \"finally : i execute always.\"); } } } Output: inside try block 17 finally : i execute always. Case 2: When the exception rises and handled by the catch block In this case, the program throws an exception but handled by the catch block, and finally block executes after the catch block. // Java program to demonstrate finally block in java // When exception rise and handled by catch import java.io.*; class GFG { CU IDOL SELF LEARNING MATERIAL (SLM) 222
public static void main(String[] args) { try { System.out.println(\"inside try block\"); // Throw an Arithmetic exception System.out.println(34 / 0); } // catch an Arithmetic exception catch (ArithmeticException e) { System.out.println( \"catch : exception handled.\"); } // Always execute finally { System.out.println(\"finally : i execute always.\"); } } } Output inside try block catch : exception handled. finally : i execute always. Case 3: When exception rise and not handled by the catch block In this case, the program throws an exception but not handled by catch so finally block execute after the try block and after the execution of finally block program terminate abnormally, But finally block execute fine. // Java program to demonstrate finally block // When exception rise and not handled by catch import java.io.*; CU IDOL SELF LEARNING MATERIAL (SLM) 223
class GFG { public static void main(String[] args) { try { System.out.println(\"Inside try block\"); // Throw an Arithmetic exception System.out.println(34 / 0); } // Cannot accept Arithmetic type exception // Only accept Null Pointer type Exception catch (NullPointerException e) { System.out.println( \"catch : exception not handled.\"); } // Always execute finally { System.out.println( \"finally : i will execute always.\"); } // This will not execute System.out.println(\"i want to run\"); } } Output Inside try block finally : i will execute always. Exception in thread \"main\" java.lang.ArithmeticException: / by zero at GFG.main(File.java:10) CU IDOL SELF LEARNING MATERIAL (SLM) 224
8.3 TYPES OF EXCEPTIONS Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions. Figure 8.3: Types of exception 8.3.1 Built-in Exception Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java. 1. ArithmeticException It is thrown when an exceptional condition has occurred in an arithmetic operation. 2. ArrayIndexOutOfBoundsException It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array. 3. ClassNotFoundException This Exception is raised when we try to access a class whose definition is not found 4. FileNotFoundException This Exception is raised when a file is not accessible or does not open. 5. IOException It is thrown when an input-output operation failed or interrupted 6. InterruptedException It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted. CU IDOL SELF LEARNING MATERIAL (SLM) 225
7. NoSuchFieldException It is thrown when a class does not contain the field (or variable) specified 8. NoSuchMethodException It is thrown when accessing a method which is not found. 9. NullPointerException This exception is raised when referring to the members of a null object. Null represents nothing 10. NumberFormatException This exception is raised when a method could not convert a string into a numeric format. 11. RuntimeException This represents any exception which occurs during runtime. 12. StringIndexOutOfBoundsException It is thrown by String class methods to indicate that an index is either negative or greater than the size of the string 8.3.2 User-Defined Exception Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, user can also create exceptions which are called ‘user-defined Exceptions’. Following steps are followed for the creation of user-defined Exception. The user should create an exception class as a subclass of Exception class. Since all the exceptions are subclasses of Exception class, the user should also make his class a subclass of it. This is done as: class MyException extends Exception We can write a default constructor in his own exception class. MyException(){} We can also create a parameterized constructor with a string as a parameter.We can use this to store exception details. We can call super class(Exception) constructor from this and send the string there. MyException(String str) { super(str); } CU IDOL SELF LEARNING MATERIAL (SLM) 226
To raise exception of user-defined type, we need to create an object to his exception class and throw it using throw clause, as: MyException me = new MyException(“Exception details”); throw me; The following program illustrates how to create own exception class MyException. Details of account numbers, customer names, and balance amounts are taken in the form of three arrays. In main() method, the details are displayed using a for-loop. At this time, check is done if in any account the balance amount is less than the minimum balance amount to be apt in the account. If it is so, then MyException is raised and a message is displayed “Balance amount is less”. 8.4 THROWING EXCEPTIONS In Java we have already defined exception classes such as ArithmeticException, NullPointerException, ArrayIndexOutOfBounds exception etc. These exceptions are set to trigger on different-2 conditions. For example when we divide a number by zero, this triggers ArithmeticException, when we try to access the array element out of its bounds then we get ArrayIndexOutOfBoundsException. We can define our own set of conditions or rules and throw an exception explicitly using throw keyword. For example, we can throw ArithmeticException when we divide number by 5, or any other numbers, what we need to do is just set the condition and throw any exception using throw keyword. Throw keyword can also be used for throwing custom exceptions, I have covered that in a separate tutorial, see Custom Exceptions in Java. Syntax of throw keyword: throw new exception_class(\"error message\"); For example: throw new ArithmeticException(\"dividing a number by 5 is not allowed in this program\"); Let’s say we have a requirement where we exception class need to only register the students when their age is less than 12 and weight is less than 40, if any of the condition is not met then the user should get an ArithmeticException with the warning message “Student is not eligible for registration”. We have implemented the logic by placing the code in the method that checks student eligibility if the entered student age and weight doesn’t met the criteria then we throw the exception using throw keyword. CU IDOL SELF LEARNING MATERIAL (SLM) 227
/* In this program we are checking the Student age * if the student age<12 and weight <40 then our program * should return that the student is not eligible for registration. */ public class ThrowExample { static void checkEligibilty(int stuage, int stuweight){ if(stuage<12 && stuweight<40) { throw new ArithmeticException(\"Student is not eligible for registration\"); } else { System.out.println(\"Student Entry is Valid!!\"); } } public static void main(String args[]){ System.out.println(\"Welcome to the Registration process!!\"); checkEligibilty(10, 39); System.out.println(\"Have a nice day..\"); } } Output: Welcome to the Registration process!!Exception in thread \"main\" java.lang.ArithmeticException: Student is not eligible for registration at beginnersbook.com.ThrowExample.checkEligibilty(ThrowExample.java:9) at beginnersbook.com.ThrowExample.main(ThrowExample.java:18) In the above example we have thrown an unchecked exception, same way we can throw unchecked and user-defined exception as well. 8.5 WRITING EXCEPTION SUBCLASSES Java provides rich set of built-in exception classes like: ArithmeticException, IOException, NullPointerException etc. all are available in the java.lang package and used in exception CU IDOL SELF LEARNING MATERIAL (SLM) 228
handling. These exceptions are already set to trigger on pre-defined conditions such as when you divide a number by zero it triggers ArithmeticException. Apart from these classes, Java allows us to create our own exception class to provide own exception implementation. These types of exceptions are called user-defined exceptions or custom exceptions. You can create your own exception simply by extending java Exception class. You can define a constructor for your Exception (not compulsory) and you can override the toString() function to display your customized message on catch. Let’s see an example. Example: Custom Exception In this example, we are creating an exception class MyException that extends the Java Exception class and class MyException extends Exception { private int ex; MyException(int a) { ex = a; } public String toString() { return \"MyException[\" + ex +\"] is less than zero\"; } } class Demo { static void sum(int a,int b) throws MyException { if(a<0) { throw new MyException(a); //calling constructor of user-defined exception class CU IDOL SELF LEARNING MATERIAL (SLM) 229
} else { System.out.println(a+b); } } public static void main(String[] args) { try { sum(-10, 10); } catch(MyException me) { System.out.println(me); //it calls the toString() method of user-defined Exception } } } 8.6 SUMMARY An Exception is an abnormal condition that arises in the code sequence at run time. Java provides a mechanism to handle the Exception that occurs that run time so that you can have your code run smoothly instead of situations that might cause your code to break at run- time. A java exception is an object that describes an exceptional condition that has occurred in the piece of code. Java exception handling is managed via five keywords try, catch, throw, throws and finally. We will learn about the usage of each of these terms subsequently. The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether CU IDOL SELF LEARNING MATERIAL (SLM) 230
exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occur or not. Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java. Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, user can also create exceptions which are called ‘user-defined Exceptions’. 8.7 KEYWORDS Finally: The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you just wish to execute, despite what happens within the protected code. Import: import is a Java keyword. It declares a Java class to use in the code below the import statement. Once a Java class is declared, then the class name can be used in the code without specifying the package the class belongs to. Use the '*' character to declare all the classes belonging to the package. ArithmeticException: ArithmeticException is an unchecked exception in Java. Usually, one would come across java. Lang. ArithmeticException: / by zero which occurs when an attempt is made to divide two numbers and the number in the denominator is zero. ArithmeticException objects may be constructed by the JVM. IOException: JavaIO Exceptions are Input/Output exceptions (I/O), and they occur whenever an input or output operation is failed or interpreted. For example, if you are trying to read in a file that does not exist, Java would throw an I/O exception. User Defined Exception: User Defined Exception or custom exception is creating your own exception class and throws that exception using 'throw' keyword. This can be done by extending the class Exception. 8.8 LEARNING ACTIVITY 1. Discuss the topic using finally clause. ________________________________________________________________________ __________________________________________________________________ 2. Conduct a seminar on throwing exception. CU IDOL SELF LEARNING MATERIAL (SLM) 231
________________________________________________________________________ __________________________________________________________________ 8.9 UNIT END QUESTIONS A. Descriptive Questions Short Questions: 1. What is finally clause? 2. What are the types of exception? 3. What is built in exception? 4. What do you mean by throwing exception? 5. What do you mean by user defined exception? Long Questions: 1. What is finally clause? Explain with example. 2. What is the list of important built-in exceptions? Explain. 3. What is the list of important user-defined exceptions? Explain. 4. What is throwing exception? Explain. 5. What is writing exception subclass? Explain. B. Multiple Choice Questions 1. Which of the following exceptions handles the situations when an illegal argument is used to invoke a method? a. Illegal Exception b. Argument Exception c. IllegalArgumentException a. IllegalMethodArgumentExcepetion 2. Which of these exceptions will be thrown if we declare an array with negative size? a. IllegalArrayException b. IllegalArraySizeExeption c. NegativeArrayException d. NegativeArraySizeExeption 3. Which of these packages contain all the Java’s built-in exceptions? CU IDOL SELF LEARNING MATERIAL (SLM) 232
a. Java.io b. Java.util c. Java.lang d. Java.net 4. Which of these exceptions will be thrown if we use null reference for an arithmetic operation? a. ArithmeticException b. NullPointerException c. IllegalAccessException d. IllegalOperationException 5. Which of these class is used to create user defined exception? a. Java.lang b. Exception c. RunTime d. System Answers 1-c, 2-d, 3-c, 4-b, 5-b 8.10 REFERENCE References John Hauser (1996). \"Handling Floating-Point Exceptions in Numeric Programs,. Bloch, Joshua (2008). \"Item 57: Use exceptions only for exceptional situations\". Effective Java (Second edition). Lajoie, Josée (March–April 1994). \"Exception handling – Supporting the runtime mechanism\". C++ Report. Textbooks Bill Venners; Bruce Eckel (August 18, 2003). \"The Trouble with Checked Exceptions. \"Unchecked Exceptions – The Controversy (The Java™ Tutorials : Essential Classes : Exceptions)\". CU IDOL SELF LEARNING MATERIAL (SLM) 233
Goodenough, John B. (1975a). Structured exception handling. Proceedings of the 2nd ACM SIGACT-SIGPLAN Website https://www.mygreatlearning.com https://www.w3schools.com https://beginnersbook.com CU IDOL SELF LEARNING MATERIAL (SLM) 234
UNIT – 9:APPLET AS JAVA APPLICATIONS 1 STRUCTURE 9.0 Learning Objectives 9.1 Introduction 9.2 Applets specific methods 9.3 Related HTML references 9.4Applet Lifecycle 9.5 Summary 9.6 Keywords 9.7 Learning Activity 9.8 Unit End Questions 9.9 References 9.0 LEARNING OBJECTIVES After studying this unit, you will be able to: Describe the applets specific methods Illustrate related to HTML references Explain Applet Lifecycle 9.1 INTRODUCTION Java was launched on 23-Jan-1996(JDK 1.0) and at that time it only supported CUI (Character User Interface) application. But in 1996 VB (Visual Basic) of Microsoft was preferred for GUI programming. So, the Java developers in hurry (i.e., within 7 days) have given the support for GUI from Operating System (OS). Now, the components like button, etc. were platform dependent (i.e., in each platform there will be different size, shape button). But they did the intersection of such components from all platforms and gave a small library which contains these intersections and it is available in AWT (Abstract Window Toolkit) technology but it doesn’t have advanced features like dialogue box, etc. Now to run Applet, java needs a browser and at that time only “Internet Explorer” was there of Microsoft but Microsoft believes in monopoly. So “SUN Micro-System” (the company which developed Java) contracted with other company known as “Netscape”(which developed Java Script) and now the “Netscape” company is also known as “Mozilla Firefox” CU IDOL SELF LEARNING MATERIAL (SLM) 235
which we all know is a browser. Now, these two companies have developed a technology called “SWING” and the benefit is that the SWING components are produced by Java itself. Therefore now it is platform-independent as well as some additional features have also been added which were not in AWT technology. So we can say that SWING is much more advanced as compared to AWT technology. An applet is a Java program that can be embedded into a web page. It runs inside the web browser and works at client side. An applet is embedded in an HTML page using the APPLET or OBJECT tag and hosted on a web server. 9.2 APPLETS SPECIFIC METHODS Applet is a Java program that can be transported over the internet and executed by a Java- enabled web-browser (if a browser is supporting the applets) or an applet can be executed using the applet viewer utility provided with JDK. An appletwe created using the Applet class, which is a part of java. applet package. Applet class provides several useful methods to give you full control over the execution of an applet. There are two types of the applet - Applets based on the AWT(Abstract Window Toolkit) package by extending its Applet class. Applets based on the Swing package by extending its JApplet class NOTE: At present, some modern versions of browsers like Google Chrome and Mozilla Firefox have stopped supporting applets; hence applets are not displayed or viewed with these browsers although some browsers like Internet Explorer and Safari are still supporting applets. Some methods of Applet class Methods Description void init() The first method to be called when an applet begins its execution. void start() Called automatically after init() method to start the execution of an applet. void stop() Called when an applet has to pause/stop its execution. void destoy() Called when an appLet us finally CU IDOL SELF LEARNING MATERIAL (SLM) 236
terminated. String getParameter(String ParameterName) Returns the value of a parameter defined in an applet Image getImage(URL url) Returns an Image object that contains an image specified at location, url void play(URL url) Plays an audio clip found at the specified at location, url showStatus(String str) Shows a message in the status window of the browser or appletviewer. Table 9.1: Method of Applet class 9.3 RELATED HTML REFERENCES As mentioned earlier, Sun currently recommends that the APPLET tag be used to start an applet from both an HTML document and from an applet viewer. An applet viewer will execute each APPLET tag that it finds in a separate window, while web browsers will allow many applets on a single page. So far, we have been using only a simplified form of the APPLET tag. Now it is time to take a closer look at it. The syntax for a fuller form of the APPLET tag is shown here. Bracketed items are optional. < APPLET [CODEBASE = codebaseURL] CODE = appletFile [ALT = alternateText] [NAME = appletInstanceName] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [< PARAM NAME = AttributeName VALUE = AttributeValue>] [< PARAM NAME = AttributeName2 VALUE = AttributeValue>] ... [HTML Displayed in the absence of Java] CU IDOL SELF LEARNING MATERIAL (SLM) 237
</APPLET> Let’s take a look at each part now. CODEBASE: CODEBASE is an optional attribute that specifies the base URL of the applet code, which is the directory that will be searched for the applet’s executable class file (specified by the CODE tag). The HTML document’s URL directory is used as the CODEBASE if this attribute is not specified. The CODEBASE does not have to be on the host from which the HTML document was read. CODE: CODE is a required attribute that gives the name of the file containing your applet’s compiled .class file. This file is relative to the code base URL of the applet, which is the directory that the HTML file was in or the directory indicated by CODEBASE if set. ALT: The ALT tag is an optional attribute used to specify a short text message that should be displayed if the browser recognizes the APPLET tag but can’t currently run Java applets. This is distinct from the alternate HTML you provide for browsers that don’t support applets. NAME: NAME is an optional attribute used to specify a name for the applet instance. Applets must be named in order for other applets on the same page to find them by name and communicate with them. To obtain an applet by name, use getApplet( ), which is defined by the AppletContext interface. WIDTH: and HEIGHT WIDTH and HEIGHT are required attributes that give the size (in pixels) of the applet display area. ALIGN: ALIGN is an optional attribute that specifies the alignment of the applet. Thisattribute is treated the same as the HTML IMG tag with these possible values: LEFT, RIGHT,TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM. VSPACE and HSPACE These attributes are optional. VSPACE specifies the space, in pixels,above and below the applet. HSPACE specifies the space, in pixels, on each side of the applet.They’re treated the same as the IMG tag’s VSPACE and HSPACE attributes. PARAM NAME and VALUE The PARAM tag allows you to specify applet-specific argumentsin an HTML page. Applets access their attributes with the getParameter( ) method. Other valid APPLET attributes include ARCHIVE, which lets you specify one or morearchive files, and OBJECT, which specifies a saved version of the applet. In general, anAPPLET tag should include only a CODE or an OBJECT attribute, but not both. 9.4 APPLET LIFECYCLE Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and works at client side. CU IDOL SELF LEARNING MATERIAL (SLM) 238
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle methods for an applet. 1. Applet is initialized. 2. Applet is started. 3. Applet is painted. 4. Applet is stopped. 5. Applet is destroyed. Figure 9.1: Applet lifecycle java.applet.Applet class For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet. Public void init(): is used to initialized the Applet. It is invoked only once. Public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet. Public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized. CU IDOL SELF LEARNING MATERIAL (SLM) 239
Public void destroy(): is used to destroy the Applet. It is invoked only once. java.awt.Component class The Component class provides 1 life cycle method of applet. Public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc. There are two ways to run an applet 1. By html file. 2. By appletViewer tool (for testing purpose). Simple example of Applet by html file: To execute the applet by html file, create an applet and compile it. After that create an html file and place the applet code in html file. Now click the html file. //First.java import java.applet.Applet; import java.awt.Graphics; public class First extends Applet{ public void paint(Graphics g){ g.drawString(\"welcome\",150,150); } } myapplet.html <html> <body> <applet code=\"First.class\" width=\"300\" height=\"300\"> </applet> </body> </html> Simple example of Applet by appletviewer tool: CU IDOL SELF LEARNING MATERIAL (SLM) 240
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is for testing purpose only. //First.java import java.applet.Applet; import java.awt.Graphics; public class First extends Applet{ public void paint(Graphics g){ g.drawString(\"welcome to applet\",150,150); } } /* <applet code=\"First.class\" width=\"300\" height=\"300\"> </applet> */ To execute the applet by appletviewer tool, write in command prompt: c:\\>javac First.java c:\\>appletviewer First.java 9.5 SUMMARY Java was launched on 23-Jan-1996(JDK 1.0) and at that time it only supported CUI (Character User Interface) application. But in 1996 VB(Visual Basic) of Microsoft was preferred for GUI programming. So, the Java developers in hurry (i.e., within 7 days) have given the support for GUI from Operating System (OS). Now to run Applet, java needs a browser and at that time only “Internet Explorer” was there of Microsoft but Microsoft believes in monopoly. So “SUN Micro- System”(the company which developed Java) contracted with other company known as “Netscape”(which developed Java Script) and now the “Netscape” company is also known as “Mozilla Firefox” which we all know is a browser. Applet is a Java program that can be transported over the internet and executed by a Java-enabled web-browser (if a browser is supporting the applets) or an applet can be executed using the appletviewer utility provided with JDK. CU IDOL SELF LEARNING MATERIAL (SLM) 241
At present, some modern versions of browsers like Google Chrome and Mozilla Firefox have stopped supporting applets; hence applets are not displayed or viewed with these browsers although some browsers like Internet Explorer and Safari are still supporting applets. Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and works at client side 9.6 KEYWORDS Applet: Java applets are used to provide interactive features to web applications and can be executed by browsers for many platforms. They are small, portable Java programs embedded in HTML pages and can run automatically when the pages are viewed. Void init():In a JApplet subclass such as MyProgram, the init() method is called automatically by the browser when the Java code is loaded and run. The term void means that the method will not return a value. The lines of code within the init() method are executed sequentially. Voidstart (): The purpose of start () is to create a separate call stack for the thread. A separate call stack is created by it, and then run() is called by JVM. Destroy (): Thedestroy () method of thread class is used to destroy the thread group and all of its subgroups. The thread group must be empty, indicating that all threads that had been in the thread group have since stopped. Voidstop (): The stop() method of thread class terminates the thread execution. Once a thread is stopped, it cannot be restarted by start() method. 9.7 LEARNING ACTIVITY 1. Conduct a seminar on applets. ________________________________________________________________________ __________________________________________________________________ 2. Discuss the topic applet lifecycle. ________________________________________________________________________ __________________________________________________________________ 9.8 UNIT END QUESTIONS A. Descriptive Questions CU IDOL SELF LEARNING MATERIAL (SLM) 242
Short Questions: 1. What is an Applet? 2. What happens when an applet is loaded? 3. What are untrusted applets? 4. What Is The Sequence For Calling The Methods By Awt For Applets? 5. When An Applet is terminated, which Sequence of Method Calls Takes Place? Long Questions: 1. Explain the life cycle of an Applet 2. What is the difference between an Applet and a Java Application? 3. How does Applet Life-Cycle Works in Java? 4. What Is The Order Of Method Invocation In An Applet? 5. What Are The Applets Life Cycle Methods? Explain Them. B. Multiple Choice Questions 1. Which of these functions is called to display the output of an applet? a. Display() b. Paint() c. DisplayApplet() d. PrintApplet() 2. Which of these methods can be used to output a string in an applet? a. Display() b. Print() c. DrawString() d. Transient() 3. Which of these operators can be used to get run time information about an object? a. GetInfo b. Info c. Instanceof d. Getinfoof CU IDOL SELF LEARNING MATERIAL (SLM) 243
4. What does an applet can play an audio file represented by the AudioClip interface in the java, applet package Causes the audio clip to replay continually in which method? a. Public void play() b. Public void loop() c. Public void stop() d. None of these 5. Which are the common security restrictions in applets? a. Applets can't load libraries or define native methods b. An applet can't read every system property c. Applets can play sounds d. Both a&b Answers 1-b, 2-c, 3-c, 4-b, 5-d 9.9 REFERENCES References Srinivas, Raghavan N. (6 July 2001). \"Java Web Start to the rescue\". Zukowski, John (1 October 1997). \"What does Sun's lawsuit against Microsoft mean for Java developers?\" Srinivas, Raghavan N. (6 July 2001). \"Java Web Start to the rescue\". Textbooks Bill Venners; Bruce Eckel (August 18, 2003). \"The Trouble with Checked Exceptions: A Conversation with Anders Hejlsberg, Part II.. \"Unchecked Exceptions – The Controversy (The Java™ Tutorials: Essential Classes : Exceptions)\". Goodenough, John B. (1975a). Structured exception handling. Proceedings of the 2nd ACM SIGACT-SIGPLAN Website https://www.mygreatlearning.com https://www.w3schools.com CU IDOL SELF LEARNING MATERIAL (SLM) 244
https://beginnersbook.com CU IDOL SELF LEARNING MATERIAL (SLM) 245
UNIT – 10:APPLET AS JAVA APPLICATIONS 2 STRUCTURE 10.0 Learning Objectives 10.1 Introduction 10.2 Creating an Applet 10.3 Displaying it using Web Browser with appletwiewer.exe 10.4 Applet v/s Applications 10.4.1 Difference between Application and Applet 10.5 Summary 10.6 Keywords 10.7 Learning Activity 10.8 Unit End Questions 10.9 References 10.0 LEARNING OBJECTIVES After studying this unit, you will be able to: Describe creating an Applet and displaying it using Web Browser with appletwiewer.exe Differentiate between Applet v/s Applications Difference between Application and Applet 10.1 INTRODUCTION Java was launched on 23-Jan-1996(JDK 1.0) and at that time it only supported CUI (Character User Interface) application. But in 1996 VB (Visual Basic) of Microsoft was preferred for GUI programming. So, the Java developers in hurry (i.e., within 7 days) have given the support for GUI from Operating System(OS). Now, the components like button, etc. were platform-dependent (i.e., in each platform there will be different size, shape button). But they did the intersection of such components from all platforms and gave a small library which contains these intersections and it is available in AWT (Abstract Window Toolkit) technology but it doesn’t have advanced features like dialogue box, etc. CU IDOL SELF LEARNING MATERIAL (SLM) 246
Now to run Applet, java needs a browser and at that time only “Internet Explorer” was there of Microsoft but Microsoft believes in monopoly. So “SUN Micro-System” (the company which developed Java) contracted with other company known as “Netscape”(which developed Java Script) and now the “Netscape” company is also known as “Mozilla Firefox” which we all know is a browser. Now, these two companies have developed a technology called “SWING” and the benefit is that the SWING components are produced by Java itself. Therefore now it is platform-independent as well as some additional features have also been added which were not in AWT technology. So we can say that SWING is much more advanced as compared to AWT technology. An applet is a Java program that can be embedded into a web page. It runs inside the web browser and works at client side. An applet is embedded in an HTML page using the APPLET or OBJECT tag and hosted on a web server. 10.2 CREATING AN APPLET Java applets are like Java applications; their creation follows the same three-step process of write, compile and run. The difference is, instead of running on your desktop, they run as part of a web page. The goal of this tutorial is to create a simple Java applet. This can be achieved by following these basic steps: Write a simple applet in Java Compile the Java source code Create an HTML page that references the applet Open the HTML page in a browser 1. Write the Java Source Code This example uses Notepad to create the Java source code file. Open up your chosen editor, and type in this code: Don’t worry too much about what the code means. For your first applet, it’s more important to see how it’s created, compiled and run. 2. Save the File Save your program file as \"FirstApplet.java\". Make sure the filename you use is correct. If you look at the code you will see the statement: It’s an instruction to call the applet class \"FirstApplet\". The filename must match this class name, and have an extension of \".java\". If your file is not saved as \"FirstApplet.java\", the Java compiler will complain and not compile your applet. CU IDOL SELF LEARNING MATERIAL (SLM) 247
3. Open a Terminal Window To open a terminal window, press the “\"Windows key\" and the letter \"R\" You will now see the \"Run Dialog\". Type \"cmd\", and press \"OK\". A terminal window will appear. Think of it as a text version of Windows Explorer; it will let you navigate to different directories on your computer, look at the files that they contain, and run any programs that you want to. This is all done by typing commands into the window. 4. The Java Compiler We need the terminal window to access the Java compiler called \"javac\". This is the program that will read the code in the FirstApplet.java file, and translate it into a language that your computer can understand. This process is called compiling. Just like Java applications, Java applets must be compiled too. To run javac from the terminal window, you need to tell your computer where it is. On some machines, it’s in a directory called \"C:\\Program Files\\Java\\jdk1.6.0_06\\bin\". If you don’t have this directory, then do a file search in Windows Explorer for \"javac\" and find out where it lives. Once you’ve found its location, type the following command into the terminal window: E.g Press Enter. The terminal window won’t do anything flashy; it will just return to the command prompt. However, the path to the compiler has now been set. 5. Change the Directory Navigate to where the FirstApplet.java file is saved. For example: \"C:\\Documents and Settings\\Paul\\My Documents\\Java\\Applets\". To change the directory in the terminal window, type in the command: E.g You can tell if you’re in the right directory by looking to the left of the cursor. 6. Compile the Applet We’re now ready to compile the applet. To do so, enter the command: After you hit Enter, the compiler will look at the code contained within the FirstApplet.java file, and attempt to compile it. If it can’t, it will display a series of errors to help you fix the code. The applet has been compiled successfully if you are returned to the command prompt without any messages. If that’s not the case, go back and check the code you’ve written. CU IDOL SELF LEARNING MATERIAL (SLM) 248
Make sure it matches the example code and re-save the file. Keep doing this until you can run javac without getting any errors. Tip: Once the applet has been successfully compiled, you will see a new file in the same directory. It will be called “FirstApplet.class”. This is the compiled version of your applet. 7. Create the HTML File It’s worth noting that so far you have followed exactly the same steps as you would if you were creating a Java application. The applet has been created and saved in a text file, and it has been compiled by the javac compiler. Java Applets differ from Java applications when it comes to running them. What’s needed now is a web page that references the FirstApplet.class file. Remember, the class file is the compiled version of your applet; this is the file your computer can understand and execute. Open up Notepad, and type in the following HTML code: Save the file as “MyWebpage.html” in the same directory as your Java applet files. This is the most important line in the webpage: When the web page is displayed, it tells the browser to open up your Java applet and run it. 8. Open the HTML Page The last step is the best one; you get to see the Java applet in action. Use Windows Explorer to navigate to the directory where the HTML page is stored. For example, \"C:\\Documents and Settings\\Paul\\My Documents\\Java\\Applets\" with the other Java applet files Double-click on the MyWebpage.html file. Your default browser will open, and the Java applet will run. Congratulations, you have created your first Java applet! 9. A Quick Recap Take a moment to review the steps you took to create the Java applet. They will be the same for every applet you make: Write the Java code in a text file Save the file Compile the code Fix any errors Reference the applet in a HTML page Run the applet by viewing the web page CU IDOL SELF LEARNING MATERIAL (SLM) 249
10.3 DISPLAYING IT USING WEB BROWSER WITH APPLETWIEWER.EXE Let's begin by writing an applet that says \"Hello, world!\" inside the browser. import java.applet.Applet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; /** * First Java Applet to say \"Hello, world\" on your web browser */ public class HelloApplet extends Applet { // save as \"HelloApplet.java\" public void paint(Graphics g) { setBackground(Color.CYAN); // set background color g.setColor(Color.BLACK); // set foreground text color g.setFont(new Font(\"Times New Roman\", Font.BOLD, 30)); // set font face, bold and size g.drawString(\"Hello, world\", 20, 80); // draw string with baseline at (20, 80) } } Compile the applet using the JDK compiler \"javac.exe\": > javac HelloApplet.java You CANNOT run the applet using JDK's Runtime \"java.exe\". Applet is a graphic program that runs inside a web browser, using the web browser's Java plug-in JRE. Applet is embedded in an HTML page (in much the same way as images, audios, videos and other programs are embedded in an HTML file). To run an applet, you need to create a HTML file, which embeds the applet. Use a text editor to create the following HTML file and save it as \"HelloApplet.html\" (or any filename of your choice). Note that HTML, unlike Java, is not case sensitive, and places no restriction on the filename. <html> <head> CU IDOL SELF LEARNING MATERIAL (SLM) 250
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334