0% found this document useful (0 votes)
15 views

5-Module - 5-09-10-2024

Uploaded by

Yashwant Sahoo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

5-Module - 5-09-10-2024

Uploaded by

Yashwant Sahoo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Module - 5

Packages in JAVA
Packages in JAVA
• A java package is a group of similar types of
classes, interfaces and sub-packages.
• Package in java can be categorized in two
form, built-in package and user-defined
package.
• There are many built-in packages such as java,
lang, awt, javax, swing, net, io, util, sql etc.
Our first package program
The keyword package is mandatory to create package programs in java
Let us now create a simple program with filename as first2.java
Let the code be as such:

package firstpack;
public class first2
{
public static void main(String a[])
{
System.out.println("this is inside first program");
}
}
How to compile java package
• Since we are not using any IDE, we have to
follow the way to compile:
Syntax:
• javac -d directory javafilename
For example
• javac -d . first2.java
• (After this you can see a folder created in the
current directory)
How to run java package program

• To run package program a qualified name e.g. firstpack.first2 etc


to run the class.
• To Compile: javac -d . first2.java
To Run: java firstpack.first2
Output: this is inside first program

• The -d is a switch that tells the compiler where to put the class file
i.e. it represents destination. We can use any directory name
like /home (in case of Linux), d:/abc (in case of windows) etc. If
we want to keep the package within the same directory, we can

.
use . (dot). The represents the current folder.
How to access package from another package?

• There are three ways to access the package


from outside the package.
• import package.*;
• import package.classname;
• fully qualified name.
Accessing package using Packagename.*

• If we use package.* then all the classes and


interfaces of this package will be accessible
but not subpackages.
• The import keyword is used to make the
classes and interface of another package
accessible to the current package.
Program for accessing using
packagename.*
• Step1: create a program with a package in it without main function
• // program contains package; class; method.
Ex: package firstpack;

public class first10


{
public void display()
{
System.out.println ("this is inside first program");
}
}
• Step 2: create another class with package and with main function
and also the package to be imported.
• EX:
package pack1; //newly created package
import firstpack.*; // firstpack is imported here so that all the
methods defined will be used in this program
class second // another class with main function
{
public static void main(String a[])
{
first2 f = new first2(); // creating object for the program in package
firstpack
f.display(); // this is the method in first2 class
}
}
To run the package program
• Step 3: compile the program without main class (Don’t
execute….)
• Ex: javac –d . First2.java
• (Since it is not having main we can’t execute)
• Step 4: Compile the program where main in present…
• Ex: javac –d . Second.java ( we can see the folder
____________created)
• Run the program: java ______________???
• OUTPUT : _________________________
• Note: If you import a package, ___________will not be
imported.
Sub-packages
• Package inside the package is known as
subpackage. The packages that come lower in
the naming hierarchy are called "sub
package" of the corresponding package higher
in the hierarchy i.e. the package that we are
putting into another package is called "sub
package".
Wrapper classes in java
A Wrapper class is a class whose object wraps or contains a primitive
data types. When we create an object to a wrapper class, it contains
a field and in this field, we can store a primitive data types. In
other words, we can wrap a primitive value into a wrapper class
object.
Need of Wrapper Classes
1.They convert primitive data types into objects. Objects are needed if
we wish to modify the arguments passed into a method (because
primitive types are passed by value).
2. The classes in java.util package handles only objects and hence
wrapper classes help in this case also.
3. Data structures in the Collection framework, such as ArrayList and
Vector, store only objects (reference types) and not primitive types.
An object is needed to support synchronization in multithreading.
Autoboxing and Unboxing in Java

Autoboxing: Converting a primitive value into an object of the


corresponding wrapper class is called autoboxing. For
example, converting int to Integer class. The Java compiler
applies autoboxing when a primitive value is:
• Passed as a parameter to a method that expects an object of the
corresponding wrapper class.
• Assigned to a variable of the corresponding wrapper class.
Unboxing: Converting an object of a wrapper type to its
corresponding primitive value is called unboxing. For example
conversion of Integer to int. The Java compiler applies
unboxing when an object of a wrapper class is:
• Passed as a parameter to a method that expects a value of the
corresponding primitive type.
• Assigned to a variable of the corresponding primitive type.
• The following table lists the primitive types and their
corresponding wrapper classes, which are used by the Java
compiler for autoboxing and unboxing:
Java program to illustrate the concept
of Autoboxing and Unboxing- autorun.java
import java.io.*;
class autoun
{
public static void main(String ar[])
{
Integer i =new Integer(10);
int j=i;
System.out.println("Value of i"+i);
System.out.println("Value of j"+j);
Character a = 'A';
char c = a;
System.out.println("the value of a "+a);
System.out.println("The value of c "+c);
}
}
This keyword
class thiskey
{
int a;
int b;

// Parameterized constructor
thiskey(int a, int b)
{
this.a = a;
this.b = b;
}

void display()
{
//Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}

public static void main(String[] args)


{
thiskey t= new thiskey(10, 20);
thiskey u = new thiskey(100,200);
t.display();
u.display();
}
}
This()
• class thiskey1
• {
• int a;
• int b;

• thiskey1()
• {
• this(10, 20);
• System.out.println("Inside default constructor \n");
• }

• thiskey1(int a, int b)
• {
• this.a = a;
• this.b = b;
• System.out.println(a+b);
• System.out.println("Inside parameterized constructor");
• }

• public static void main(String[] args)
• {
• thiskey1 t = new thiskey1();
• }
• }
Module – 5

Exception handling in JAVA


Exception Handling in Java
• It is the mechanism to accomplish
normal flow of the application to handle
runtime errors such as ClassNotFound,
IO, SQL, Remote etc…
• In java, exception is an event that
disrupts the normal flow of the program.
It is an object which is thrown at
runtime.
Hierarchy of Java Exception classes
Types of Exception
• There are mainly two types of
exceptions: checked and unchecked
exception. The sun microsystem says
there are three types of exceptions:
• Checked Exception
• Unchecked Exception
• Error
Difference between checked and unchecked exceptions

1) Checked Exception
The classes that extend Throwable class except RuntimeException
and Error are known as checked exceptions e.g.IOException,
SQLException etc. Checked exceptions are checked at compile-
time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are
not checked at compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Common exceptions
• 1. 50/0  Arithmetic exception
• 2. String s = null, S.o.p(s.length)
_______________________
• 3. int a[]=new int[5];
a[6] = 20;  _________________
4. String s= “HELLLO”;
S.o.p(Interger.parseInt(S));  _________
Java Exception Handling Keywords
• There are 5 keywords used in java exception handling.
• try -> try block is used to enclose the code that might
throw an exception. It must be used within the method
• Catch -> Java try block must be followed by either
catch or finally block. catch block is used to handle the
Exception. multiple catch block with a single try is also
possible
• Finally-> Java finally blockis always executed whether
exception is handled or not. Java finally block follows
try or catch block.
• 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. When
a throw statement is encountered and
executed, execution of the current method is
stopped and returned to the caller
• Throws ->Whereas the throws keyword is used
to declare that a method may throw one or
some exceptions
Syntax
java try-catch
• try{
• //code that may throw exception
• }catch(Exception_class_Name ref){}
try-finally block
• try{
• //code that may throw exception
• }finally{}
Example program for arithmetic exception
// program using exception
// program with out exception class exp1
class exp1 {
{ public static void main(String
public static void main(String ar[]) ar[])
{
{
try
int a = 50/0; {
System.out.println("the value of a int a = 50/0;
"+a); System.out.println("the value
} of a "+a);
} }catch(Exception e)
{System.out.println(e);}
System.out.println("lines of
coding continues");
How exception is handled using try-catch
Multiple catch block
class exp2
{
public static void main(String ar[])
{
try
{
String s = "helo";
int a[] = new int[5];
a[5]= Integer.parseInt(s);
} catch (NumberFormatException e )
{
System.out.println("\nNumber format:"+e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("\nArray index: "+e);
}
catch(Exception e){}
System.out.println("\nprogram continues...");
}
}
Conclusions from multiple catch
1. At a time only one Exception is occured and
at a time only one catch block is executed.
2. All catch blocks must be ordered from most
specific to most general i.e. catch for
ArithmeticException must come before
catch for Exception . (Get the answer for this
conclusion)
Nested try-catch block
• Some cases where certain set of code causes
some error and another set of code causes
another error then we are in need of nested
try-catch block..(Example program exp3.java)
• class exp3
• { try
• public static void main(String ar[]) {
• int a[] = new int[5];
{
a[5]= 100;
• try }catch(ArrayIndexOutOfBoundsException
• { e)
• try {
• { System.out.println("\nArray index: "+e);
• String s = "helo"; }
• }catch(Exception e)
int a = Integer.parseInt(s);
{
• } catch (NumberFormatException System.out.println("General
e ){ exeception.....");
• System.out.println("\nNumber }
format:"+e); System.out.println("\nprogram
• } continues...");
}
}
Finally block
• Java finally block is a block that is used to
execute important code such as closing
connection, stream etc. Java finally blockis
always executed whether exception is handled
or not. Java finally block follows try or
catch block.
Finally block
• class finally2
• {
• public static void main(String args[])
• {
• try
• {
• int a[] = new int[10];
• a[23]=45;
• }

• finally
• {
• int a=10, b=0;
• int c = a/b;
• System.out.println(c);
• System.out.println("This block will execute even if the exception is present but not

• handled");
• }

• System.out.println("program continues..");
• }
• }
Try-catch inside finally block
• class finally2
• {
• public static void main(String args[])
• {
• try
• {
• int a[] = new int[10];
• a[23]=45;
• } catch(Exception e) {System.out.println(e);}

• finally
• {
• try
• {
• int a=10, b=0;
• int c = a/b;
• System.out.println(c);
• System.out.println("This block will execute even if the exception is present but not

• handled");
• }catch(Exception e){System.out.println(e);}

• }

• System.out.println("program continues..");
• }
User-defined Exception
• If you are creating your own Exception that is
known as custom exception or user-defined
exception. Java custom exceptions are used to
customize the exception according to user
need.
• //write a exception program to indicate person to pay the income tax or not

• import java.util.*;
• class Incometax extends Exception
• {
• Incometax(String s)
• {
• super(s);
• }
• }

• class userdefinedexception
• {

• static void check(int salary) throws Incometax
• {
• if(salary <100000)
• throw new Incometax("No need to pay tax");
• else
• System.out.println("Pay your tax");
• }

• public static void main(String args[])
• {
• int n;
• Scanner s = new Scanner(System.in);
• System.out.println("Enter your annual salary");
• n = s.nextInt();
• try{
• check(n);
• }catch(Exception e){System.out.println("Exception caught: "+e);}

• System.out.println("sucess...");
• }
Advantage of Exception Handling
• to maintain the normal flow of the
application.
• Ie. Suppose there is 6lines of coding
statements in our program and there occurs
an exception at statement 5, rest of the code
will not be executed i.e. statement 6 to 10 will
not run. If we perform exception handling,
rest of the statement will be executed. That is
why we use exception handling in java.
Practise Programs- Exception Handling
1. Write a class to sort the given set of n integers in descending order. Include a try block
to locate the array index out of bound exception and catch it.

2. Write a program to calculate the grade of a student. Enter marks for minimum 5
subjects. While entering marks if the mark is negative throw NegativeMarkException
and if the mark is greater than 100 throw OutofRangeException.

3. Write a Java Program to create a class Employee containing EmpCode, name, age,
experience. Create a constructor to initialize the data members. Create a
display( ) method to display the details. Create a check( )method to check for the
following conditions:
• Length of EmpCode should be exactly 6
• Maximum characters of name is 30
• Age cannot be less than 18 ormore than 58
• Experience cannot exceed age-18

4. Write a java program to get the age of the user, if the age of the user is less than 18, give
a message that “ you are not eligible for voting””, else allow the user to provide their
Thank you
ALL THE BEST

You might also like