module4_java4
module4_java4
Email: [email protected]
[email protected]
RV Institute of Technology and Management®
package pkg;
Java uses file system directories to store packages. For example, the .class files for any classes
you declare to be part of MyPackage must be stored in a directory called MyPackage.
Package pkg1[.pkg2[.pkg3]];
• In real life situation there may arise scenarios where we need to define files of the same
name. This may lead to ―name-space collisions‖. Packages are a way of avoiding
space collisions.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible
but not sub packages. The import keyword is used to make the classes and interface of
another package accessible to the current package.
//save by A.java
package pack;
public class A{
public void msg()
{System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B
{ public static void main(String args[])
}
}
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully
qualified nameobj.msg();}}
Access Specifiers
• private: accessible only in the class
• default : so-called ―package‖ access — accessible only in the same package
• protected: accessible (inherited) by subclasses, and accessible by code in same
package
• public: accessible anywhere the class is accessible, and inherited by subclasses
Notice that private protected is not syntactically legal. Comparison of access specifier is as
shown in Table 4.1
ExceptionHandlinginJava
An exception(or exceptional event )is a problem that arises during the execution of a program. When an Exception
occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is
not recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an exception occurs.
A user has entered an invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the JVM has run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by physical resources
that have failed in some manner.
Errors indicate serious problems and abnormal conditions that most applications should not
try to handle. Error defines problems that are not expected to be caught under normal
circumstances by our program. For example, memory error, hardware error, JVM error etc.
Exceptions are conditions within the code. A developer can handle such conditions and take
necessary corrective actions.
Fewexamples–
• Divide By Zero exception
• Null Pointer Exception
• Arithmetic Exception
• Array Index Ou tOf Bounds Exception
Exception hierarchy
Figure3.7:Exception Hierarchy
a) try-catch–
try is the start of the block and catch is at the end of try block to handle the
exceptions. We can have multiple catch blocks with a try an try-catch block can be nested
also catch block requires a parameter that should be of type Exception.
A catch block must be associated with a try block. The corresponding catch block
executes if an exception of a particular type occurs within the try block.
import java.io.*;
For example, if an arithmetic exception occurs in try block then the statements enclosed in
catch block for arithmetic exception executes.
All the statements in the catch block will be executed and then the program continues.
If the exception type of exception, matches with the first catch block it gets caught, if not the
exception is passed down to the next catch block.
classExample2{
public static void main(String args[]){
try{
int a[]=newi nt[7];
a[4]=30/0;
System.out.println("Firstprintstatementintryblock");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsExceptione){
System.out.println("Warning:
ArrayIndexOutOfBoundsException");
}
catch(Exceptione){
System.out.println("Warning:SomeOtherexception");
}
System.out.println("Outoftry-catchblock...");
}
}
Warning:ArithmeticException
Out of try-catch block...
c) Javafinally block
Java finally block is a block that is used to execute important code such as closing connection,stream etc.Java
finally block is always executed whether exception is handled or not.
Finallyblockisoptionalandcanbeusedonlywithtry-catchblock.Sinceexceptionhalts the process of execution, we
might have some resources open that will not get closed, so we can use finally block. finally block gets executed
always, whether exception occurred or not.
classTestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerExceptione)
{
System.out.println(e);
}
finally
{
System.out.println("finallyblockisalwaysexecuted");
}
System.out.println("restofthecode...");
}
}
Exception Handling is mainly used to handle the checked exceptions. If there occurs
any unchecked exception such as Null Pointer Exception, it is programmers ‘fault that he is
not performing checkup before the code is used.
throws–Whenwearethrowinganyexceptioninamethodandnothandlingit,thenweneed to use
throws keyword in method signature to let caller program knows the exceptions that
mightbethrownbythemethod.Thecallermethodmighthandletheseexceptionsorpropagate it to
its caller method using throws keyword. We can provide multiple exceptions in the throws
clause and it can be used with main () method also.
throw–
We know that if any exception occurs, an exception object is getting created and then
Java runtime starts processing to handle them.Sometime we might want to generate exception
explicitly in our code, for example in a user authentication program we should throw
exception to client if the password is null. throw keyword is used to throw exception to the
runtime to handle it.
importjava.io.*;
class M
{
voidmethod()throwsIOException
{
thrownewIOException("deviceerror");
}
}
classTestthrows4
{
publicstaticvoidmain(Stringargs[])throws IOException
{
Mm=newM();
m.method();
System.out.println("normalflow...");
}
}
Warning:Exceptioninthread"main"java.io.IOException:deviceerror
illustrates final:classBike
{
finalvoid run()
{
System.out.println("running");
}
}
classHondaextends Bike
{
voidrun()
{
System.out.println("runningsafelywith100kmph");
}
public static void
main(Stringargs[]){Honda
honda= new Honda();
honda.run();
}
}
Warning:Complie Time Error as Finalmethods cannot be overridden
b) Final Class:
Sometimes you will want to prevent a class from being inherited. To do this, precede the class
declaration with final. Declaring a class as final implicitly declares all of its methods as final,
too. As you might expect, it is illegal to declare a class as both abstract and final since an
abstract class is incomplete by itself and relies upon its subclasses to provide complete
implementations. Here is an example of a final class:
finalclassBike{}
classHonda1extendsBike{
voidrun(){System.out.println("runningsafelywith100kmph");}
publicstaticvoidmain(Stringargs[])
{Honda1honda=newHonda();
honda.run();
}
}
Warning:CompileTimeError
c) Final variable
If you make any variable as final, you cannot change the value of finalvariable (It will be
constant).
Class Bike
{
finalintspeedlimit=90;//final
variablevoid run()
{
speedlimit=400;
}
public static void main(String
args[]){Bike9obj=newBike9();
obj.run();//CompileTimeError
}
}
Java exceptions cover almost all the general type of exceptions that may occur in the programming.
However, we sometimes need to create custom exceptions.
13.
14. // method to check the age
15. static void validate (int age) throws InvalidAgeException{
16. if(age < 18){
17.
18. // throw an object of user defined exception
19. throw new InvalidAgeException("age is not valid to vote");
20. }
21. else {
22. System.out.println("welcome to vote");
23. }
24. }
25.
26. // main method
27. public static void main(String args[])
28. {
29. try
30. {
31. // calling the method
32. validate(13);
33. }
34. catch (InvalidAgeException ex)
35. {
36. System.out.println("Caught the exception");
37.
38. // printing the message from InvalidAgeException object
39. System.out.println("Exception occured: " + ex);
40. }
41.
42. System.out.println("rest of the code...");
43. }
44. }
CHAINED EXCEPTION
In Java, a chained exception is a technique that enables programmers to associate one Exception with
another. By providing additional information about a specific exception, debugging can be made easier.
A chained exception is created by wrapping an existing exception in a new exception, which becomes the
root cause of the new Exception.
The new Exception can provide additional information, while the original Exception contains the actual
error message and stack trace. It makes it easier to determine and fix the problem's source. Chained
exceptions are especially useful when an exception is thrown due to another exception.
In Java, a chained exception is created using one of the constructors of the exception class.
Throwable Class
Constructors and methods for supporting chained exceptions are available in the Throwable class. Let's
start by taking a look at the constructors.
Throwable(Throwable cause): A Java constructor creates a new exception object with a specified cause
exception.
Throwable(String desc, Throwable cause): A Java constructor creates a new Throwable object with a
message and a cause. It allows for chaining exceptions and providing more detailed information about
errors.
getCause(): It is a Java method of the Throwable class that returns the cause of the current Exception. It
allows for accessing the Exception or error that triggered the current Exception to be thrown.
try {
String s = null;
} catch (NumberFormatException e) {
// set the cause of the new Exception to a new NullPointerException with the message " It is actua
l cause of the exception "
throw ex;
}
III- Semester Object Oriented Programming with JAVA(BCS306A) 14
RV Institute of Technology and Management®
Output:
Filename: NonChainedExceptionExample.java
import java.util.Scanner;
// Defining the main method that will be executed when the program runs
scanner.close();
try {
if (num < 0) {
// Dividing 100 by the input integer and storing the result in the variable result
} catch (IllegalArgumentException e) {
// Catching the IllegalArgumentException and printing an error message with the Exception's message
} catch (ArithmeticException e) {
// Catching the ArithmeticException and printing an error message for division by zero
Output:
Filename: ChainedExceptionExample.java
// create a new Scanner object to read user input from the console
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
// read the user's input as an integer
int num = scanner.nextInt();
scanner.close();
try {
// check if the input number is positive, throw an exception if it's not
if (num < 0) {
throw new IllegalArgumentException("Number must be positive");
}
int result = 100 / num;
System.out.println("Result: " + result);
} catch (IllegalArgumentException e) {
// create a new exception with the original Exception as the cause
throw new RuntimeException("Invalid input", e);
} catch (ArithmeticException e) {
// create a new exception with the original Exception as the cause
throw new RuntimeException("Error: division by zero", e);
}
}
}
Output: