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

OOP Through Java UNIT-4 Material

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

OOP Through Java UNIT-4 Material

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

UNIT-4

Packages
A package is a container of classes and interfaces A package represents a directory that
contains related group of classes and interfaces For example, when we write statemens like:
import javaio*;
Here we are importing classes of javaio package Here, java is a directory name and io is
another sub directory within it The „*‟ represents all the classes and interfaces of that io sub
directory We can create our own packages called user-defined packages or extend the
available packages User-defined packages can also be imported into other classes and used
exactly in the same way as the Built-in packages Packages provide reusability

General form for creating a package:


package packagename;
eg: package pack;
The first statement in the program must be package statement while creating a package
While creating a package except instance variables, declare all the members and the class
itself as public then only the public members are available outside the package to other
programs
Program 1: Write a program to create a package pack with Addition class
//creating a package
package pack;
public class Addition
{
private double d1,d2;
public Addition(double a,double b)
{
d1 = a;
d2 =b;
}
public void sum()
{
System.out.println ("Sum of two given numbers is : " + (d1+d2) );
}
}
Compiling the above program:
The –d option tells the Java compiler to create a separate directory and place the class file in
that directory (package) The () dot after –d indicates that the package should be created in the
current directory So, out package pack with Addition class is ready

Program 2: Write a program to use the Addition class of package pack


//Using the package pack
import pack.Addition;
class Use
{
public static void main(String args[])
{
Addition ob1 = new Addition(10,20);
ob1.sum();
}
}
Output:

Program 3: Write a program to add one more class Subtraction to the same package pack
//Adding one more class to package pack:
package pack;
public class Subtraction
{
private double d1,d2;
public Subtraction(double a, double b)
{
d1 = a;
d2 =b;
}
public void difference()
{
System.out.println ("Sum of two given numbers is : " + (d1 - d2) );
}
}
Compiling the above program:
Program 4: Write a program to access all the classes in the package pack
//To import all the classes and interfaces in a class using import pack*;
import pack*;
class Use
{
public static void main(String args[])
{
Addition ob1 = new Addition(105,206);
ob1.sum();
Subtraction ob2 = new Subtraction(302,4011);
ob2.difference();
}
}
In this case, please be sure that any of the Additionjava and Subtractionjava programs will not
exist in the current directory Delete them from the current directory as they cause confusion
for the Java compiler The compiler looks for byte code in Additionjava and Subtractionjava
files and there it gets no byte code and hence it flags some errors

Output:

If the package pack is available in different directory, in that case the compiler should be given
information regarding the package location by mentioning the directory name of the package in
the classpath The CLASSPATH is an environment variable that tells the Java compiler where to
look for class files to import If our package exists in e:\sub then we need to set class path as
follows:

We are setting the classpath to e:\sub directory and current directory () and
%CLASSPATH% means retain the already available classpath as it is

Creating Sub package in a package: We can create sub package in a package in the format:
package packagename.subpackagename;
eg: package pack1.pack2;
Here, we are creating pack2 subpackage which is created inside pack1 package To use the
classes and interfaces of pack2, we can write import statement as:
import pack1.pack2;
Program 5: Program to show how to create a subpackage in a package
//Creating a subpackage in a package
package pack1.pack2;
public class Sample
{
public void show ()
{
System.out.println ("Hello Java Learners");
}
}
Compiling the above program:

Access Specifier: Specifies the scope of the data members, class and methods private members of the
class are available with in the class only The scope of private members of the class is “CLASS
SCOPE” public members of the class are available anywhere The scope of public members of the class
is "GLOBAL SCOPE" default members of the class are available with in the class, outside the class
and in its sub class of same package It is not available outside the package So the scope of default
members of the class is "PACKAGE SCOPE" protected members of the class are available with in the
class, outside the class and in its sub class of same package and also available to subclasses in different
package also
Class Member Access private No Modifier protected public
Same class Yes Yes Yes Yes
Same package subclass No Yes Yes Yes
Same package non-subclass No Yes Yes Yes
Different package subclass No No Yes Yes
Different package non-subclass No No No Yes

Program 6: Write a program to create class A with different access specifiers


//create a package same
package same;
public class A
{
private int a=1;
public int b = 2;
protected int c = 3;
int d = 4;
}
Compiling the above program:
Program 7: Write a program for creating class B in the same package
//class B of same package
package same;
import sameA;
public class B
{
public static void main(String args[])
{
A obj = new A();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}

Compiling the above program:

Program 8: Write a program for creating class C of another package


package another;
import same.A;
public class C extends A
{
public static void main(String args[])
{
C obj = new C();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}

Compiling the above program:


Java.lang package
Provides classes that are fundamental to the design of the Java programming language. The most
important classes are Object, which is the root of the class hierarchy, and Class, instances of which
represent classes at run time.

Following are the Important Classes in Java. Lang package:

1. Boolean: The Boolean class wraps a value of the primitive type boolean in an object.
2. Byte: The Byte class wraps a value of primitive type byte in an object.
3. Character – Set 1, Set 2: The Character class wraps a value of the primitive type char in an object.
4. Character.Subset: Instances of this class represent particular subsets of the Unicode character set.
5. Character.UnicodeBlock: A family of character subsets representing the character blocks in the
Unicode specification.
6. Class – Set 1, Set 2 : Instances of the class Class represent classes and interfaces in a running Java
application.
7. ClassLoader: A class loader is an object that is responsible for loading classes.
8. ClassValue: Lazily associate a computed value with (potentially) every type.
9. Compiler: The Compiler class is provided to support Java-to-native-code compilers and related
services.
10. Double: The Double class wraps a value of the primitive type double in an object.
11. Enum: This is the common base class of all Java language enumeration types.
12. Float: The Float class wraps a value of primitive type float in an object.
13. InheritableThreadLocal: This class extends ThreadLocal to provide inheritance of values from
parent thread to child thread: when a child thread is created, the child receives initial values for all
inheritable thread-local variables for which the parent has values.
14. Integer: The Integer class wraps a value of the primitive type int in an object.
15. Long: The Long class wraps a value of the primitive type long in an object.
16. Math – Set 1, Set 2: The class Math contains methods for performing basic numeric operations such
as the elementary exponential, logarithm, square root, and trigonometric functions.
17. Number: The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte,
Double, Float, Integer, Long, and Short.
18. Object: Class Object is the root of the class hierarchy.
19. Package: Package objects contain version information about the implementation and specification of a
Java package.
20. Process: The ProcessBuilder.start() and Runtime.exec methods create a native process and return an
instance of a subclass of Process that can be used to control the process and obtain information about
it.
21. ProcessBuilder: This class is used to create operating system processes.
22. ProcessBuilder.Redirect: Represents a source of subprocess input or a destination of subprocess output.
23. Runtime: Every Java application has a single instance of class Runtime that allows the application to
interface with the environment in which the application is running.
24. RuntimePermission: This class is for runtime permissions.
25. SecurityManager: The security manager is a class that allows applications to implement a security
policy.
26. Short: The Short class wraps a value of primitive type short in an object.
27. StackTraceElement: An element in a stack trace, as returned by Throwable.getStackTrace().
28. StrictMath- Set1, Set2: The class StrictMath contains methods for performing basic numeric
operations such as the elementary exponential, logarithm, square root, and trigonometric functions.
29. String- Set1, Set2: The String class represents character strings.
30. StringBuffer: A thread-safe, mutable sequence of characters.
31. StringBuilder: A mutable sequence of characters.
32. System: The System class contains several useful class fields and methods.
33. Thread: A thread is a thread of execution in a program.
34. ThreadGroup: A thread group represents a set of threads.
35. ThreadLocal: This class provides thread-local variables.
36. Throwable: The Throwable class is the superclass of all errors and exceptions in the Java language.
37. Void: The Void class is an uninstantiable placeholder class to hold a reference to the Class object
representing the Java keyword void.
Program 8: Write a program to print the methods in Object class and its methods count.

import
java.lang.reflect.*;
class TestingClass
{
public static void main(String args[])throws Exception
{
int count=0;
Class
c=Class.forName("java.lang.Object");
Method []m=c.getDeclaredMethods();
for(Method m1:m)
{
count++;
System.out.println(m1+" Method Name is "+m1.getName());
}
System.out.println("The no of Methods in this class is "+count);
}
}

Compiling the above program:


Packages in JAVA SE:-
In Java SE (Standard Edition), packages are used to group related classes, interfaces, and sub-
packages. They provide access control, help prevent name conflicts, and make it easier to locate and
use classes in a large project. Java SE has several core packages that are part of the Java API.
Here’s an overview of some key packages in Java SE:
1. java.lang
 The java.lang package is automatically imported into every Java program.
 It contains fundamental classes and interfaces for the Java language.
 Important classes include:

 Object: The root class of the Java class hierarchy.


 String: Represents a sequence of characters.
 Math: Provides mathematical operations like square root, power, and trigonometric
functions.
 System: Contains methods like System.out for standard input and output.
 Thread: Represents a thread of execution in a program.
 Exception and RuntimeException: For exception handling in Java.

2. java.util
 The java.util package contains utility classes like data structures, date and time facilities, and
more.
 Key classes and interfaces include:

 ArrayList, LinkedList, HashSet, TreeSet: Data structures implementing the List and
Set interfaces.
 HashMap, TreeMap: Data structures for mapping keys to values (Map interface).
 Date and Calendar: Classes for handling dates and times (though newer java.time
package is preferred).
 Collections: Provides utility methods for collection manipulation (sorting, searching,
etc.).
 Scanner: Used to parse and tokenize input (commonly used for console input).

3. java.io
 The java.io package provides classes for input/output operations, especially working with
files, streams, and serialization.
 Key classes include:

 File: Represents a file or directory.


 InputStream, OutputStream: Abstract classes for reading and writing binary data.
 Reader, Writer: Abstract classes for reading and writing character streams.
 BufferedReader, BufferedWriter: For efficient reading and writing using buffers.
 Serializable: An interface that enables an object’s state to be written to a stream.

4. java.nio (New I/O)


 The java.nio package offers more efficient I/O operations compared to java.io, using non-
blocking I/O and buffers.
 Important classes include:
 ByteBuffer, CharBuffer: Buffers for handling different types of data.
 Files: Utility class for working with file systems and directories.
 Channels: For efficient reading and writing of data from sources like files, sockets, etc.
5. java.net
 The java.net package provides classes for network programming (e.g., handling URLs,
sockets, and IP addresses).
 Key classes include:
o URL: Represents a Uniform Resource Locator.
o Socket: Implements client sockets (TCP connections).
o ServerSocket: Implements server-side sockets.
o HttpURLConnection: Manages HTTP connections.

6. java.sql
 The java.sql package provides classes and interfaces for database access and SQL operations.
 Important classes/interfaces include:

 Connection: Represents a connection to a database.


 Statement, PreparedStatement: Used to execute SQL queries.
 ResultSet: Represents the result of an SQL query.
 DriverManager: Manages database drivers.

7. java.time
 The java.time package, introduced in Java 8, provides a modern API for date and time.
 Key classes include:
 LocalDate, LocalTime, LocalDateTime: Represent date, time, and both, respectively.
 ZonedDateTime: Represents date-time with time zone.
 Duration, Period: Measure time spans (seconds, days, months, etc.).
 DateTimeFormatter: Formats and parses date-time objects.

8. java.security
 The java.security package contains classes and interfaces related to security, including
cryptography, authentication, and authorization.
 Key classes include:
 MessageDigest: Provides functionality for generating message digests (hashes).
 Key, KeyPair: Represents cryptographic keys.
 Signature: Used for generating and verifying digital signatures.
 AccessControlException: Represents an exception when an access control violation
occurs.

9. javax.swing

 The javax.swing package provides classes for building graphical user interfaces (GUIs).
 Key components include:
o JFrame: Represents the main window of a Swing application.
o JButton, JLabel, JTextField: GUI components for buttons, labels, text fields, etc.
o JPanel: A container that can hold and organize other components.
o JTable: A component for displaying tabular data.

10. java.util.concurrent

 The java.util.concurrent package offers utilities for concurrent programming, including


thread pools, synchronization mechanisms, and atomic variables.
 Important classes/interfaces include:
o ExecutorService: Manages thread pools and asynchronous tasks.
o CountDownLatch, Semaphore, CyclicBarrier: Provide synchronization mechanisms.
o Future: Represents the result of an asynchronous computation.
11. java.awt

 The java.awt package provides classes for creating user interfaces and graphics (it’s older
than javax.swing).
 Key classes include:
o Frame, Panel, Button: Components for building GUIs.
o Graphics: A class for drawing shapes and text.
o Color, Font: Classes for working with colors and fonts.

12. java.rmi

 The java.rmi package provides classes for Remote Method Invocation (RMI), allowing
objects to invoke methods on remote objects across a network.
 Key classes include:
o Remote: A marker interface for remote objects.
o Naming: Provides methods for binding and looking up remote objects in the registry.

Classes in Packages:
1. Class Object

In Java, Object is the root class from which all classes implicitly inherit. It defines the most general
methods that are applicable to all objects in Java. Some of its important methods are:

 toString(): Returns a string representation of the object.


 equals(Object obj): Determines if two objects are equal.
 hashCode(): Returns a hash code value for the object.
 clone(): Creates and returns a copy of the object.
 finalize(): Called by the garbage collector when the object is no longer in use.

Every class in Java is a subclass of the Object class, either directly or indirectly.

2. Class Math

The Math class in Java provides basic mathematical operations like exponentiation, logarithms, square
roots, and trigonometric functions. It’s part of the java.lang package, so no import is needed. Key
methods include:

 abs(double a): Returns the absolute value.


 pow(double a, double b): Returns a raised to the power of b.
 sqrt(double a): Returns the square root of a.
 sin(double a), cos(double a), tan(double a): Trigonometric functions.
 random(): Returns a random number between 0.0 and 1.0.
 max(a, b), min(a, b): Returns the maximum or minimum of two values.

3. Java Util Classes


The java.util package contains utility classes for data structures, collections, and other helpful utilities.
Some important classes include:
 ArrayList: A resizable array implementation of the List interface.
 HashMap: A hash table-based implementation of the Map interface, which stores key-value
pairs.
 HashSet: A collection that contains no duplicate elements, based on a hash table.
 Collections: Provides static methods for manipulating collections (e.g., sorting, searching).
 Date: Represents a specific instant in time.
 Scanner: A class for parsing input (typically from the console).
4. Java Util Interfaces
Java provides several important interfaces in the java.util package:
 List: An ordered collection (also known as a sequence), allowing duplicate elements. Examples:
ArrayList, LinkedList.
 Set: A collection that contains no duplicate elements. Examples: HashSet, TreeSet.
 Map: A collection of key-value pairs. Examples: HashMap, TreeMap.
 Iterator: Allows traversal through a collection, one element at a time.
 Comparable: Used for objects that have a natural ordering, enabling comparison.
 Comparator: Provides custom orderings for objects in a collection.
EXCEPTIONS

An error in a program is called bug Removing errors from program is called debugging There
are basically three types of errors in the Java program:
Compile time errors: Errors which occur due to syntax or format is called compile time
errors. These errors are detected by java compiler at compilation time. Desk checking is
solution for compile-time errors
Runtime errors: These are the errors that represent computer inefficiency. Insufficient
memory to store data or inability of the microprocessor to execute some statement is
examples to runtime errors Runtime errors are detected by JVM atruntime
Logical errors: These are the errors that occur due to bad logic in the program These errors
are rectified by comparing the outputs of the program manually

Exception: An abnormal event in a program is called Exception Exception may occurat compile
time or at runtime
Exceptions which occur at compile time are called Checked exceptions
eg: ClassNotFoundException, NoSuchMethodException, NoSuchFieldExceptionetc
Exceptions which occur at run time are called Unchecked exceptionseg:
ArrayIndexOutOfBoundsException, ArithmeticException,
NumberFormatException etc

Exception Handling: Exceptions are represented as classes in java


An exception can be handled by the programmer where as an error cannot be handled by the
programmer When there is an exception the programmer should do the following tasks:
If the programmer suspects any exception in program statements, he should write them
inside try block
try
{
statements;
}
When there is an exception in try block JVM will not terminate the program abnormally
JVM stores exception details in an exception stack and then JVM jumps into catch block The
programmer should display exception details and any message to the user in catch block

catch ( ExceptionClass obj)


{
statements;
}
Programmer should close all the files and databases by writing them inside finallyblock Finally
block is executed whether there is an exception or not
finally
{
statements;
}
Performing above tasks is called Exception Handling

Program 1: Write a program which tells the use of try, catch and finally blockException
example
Class ExceptionExample
{
public static void main(String args[])
{
try{
System.out.println ("open files");int
n=args.length; System.out.println(
System.out.println ("a="+a);
int b[]={10,19,12,13};
b[50]=100;
}
catch (ArithmeticException ae)
{
System.out.println ("ae");
System.out.println ("plz type data while executing the program");
}
catch (ArrayIndexOutOfBoundsException aie)
{
System.out.println ("aie");
System.out.println ("please see that array index is not within the range");
}
finally
{
System.out.println ("close files");
}
}
}
Output:

.Even though multiple exceptions are found in the program, only one exception is raised at a
time.We can handle multiple exceptions by writing multiple catch blocks.A single try block
can be followed by several catch blocks.Catch block does not always exit without a try, but a
try block exit without a catch block.Finally block is always executed whether there is an
exception or not

throws Clause: throws clause is useful to escape from handling an exception throws clause is
useful to throw out any exception without handling it

Program 2: Write a program which shows the use of throws clause not handling theexception
import javaio*; class Sample
{
void accept( )throws IOException
{
BufferedReader br=new BufferedReader (new
InputStreamReader(System.in)); System.out.print ("enter ur name:
");
String name=br.readLine ( );
System.out.println ("Hai "+name);
}
}
class ExceptionNotHandle
{
public static void main (String args[])throws IOException
{
Sample s=new Sample ( );
saccept ( );
}
}
Output:

throw Clause: throw clause can be used to throw out user defined exceptions It isuseful to
create an exception object and throw it out of try block
Program 3: Write a program which shows the use of throw clause
//ThrowExample
class ThrowDemo
{
static void Demo( )
{
try
{
System.out.println ("inside method");
throw new NullPointerException("my data");

}
catch (NullPointerException ne)
{
System.out.println ("ne");
}
}
public static void main(String args[])
{
ThrowDemoDemo ( );
}
}
Output:

Types of Exceptions:
Built-in exceptions: These are the exceptions which are already available in java
eg:
 ArithmeticException,
 ArrayIndexOutOfBoundsException,
 NullPointerException,
 StringIndexOutOfBoundsException,
 NoSuchMethodException,
 InterruptedException,
 ClassNotFoundException,
 FileNotFoundException,
 NumberFormatException,
 RuntimeException etc

User-defined exceptions: - These are the exceptions created by the programmerWrite user
exception class extending Exception class
eg: class MyException extends Exception
Write a default constructor in the user exception class
eg: MyException ( ) { }

Write a parameterized constructor with String as a parameter, from there call the
parameterized constructor of Exception class
eg: MyException (String str)
{
super (str);
}
Whenever required create user exception object and throw it using throw
statement
Ex: - throw me;

Program 4: Write a program to throw a user defined exception


// user defined exception
class MyException extends Exception
{
int accno[] = {1001,1002,1003,1004,1005};

String name[] =
{"Hari","Siva","Bhanu","Rama","Chandu"}; double bal[]
= {2000,3500,1500,1000,6000};
MyException()
{
}
MyException(String str)
{
super(str);
}

public static void main(String args[])


{
try
{
MyException me = new MyException("");
System.out.println("AccNo \t Name \t Balance");
for(int i=0;i<5;i++)
{
System.out.println(me.accno[i]+ "\t" + me.name[i] + "\t" +me.bal[i] );if(
me.bal[i] < 2000 )
{
MyException me1 = new MyException("Insufficient Balance");throw
me1;
}
}
}
catch(MyException e)
{
e.printStackTrace();
}
}
}
OUTPUT

In Java, exceptions are categorized into two main types: checked exceptions and unchecked
exceptions. The distinction lies in whether the compiler checks for the exception handling at
compile-time or not.
1. Checked Exceptions
 Definition: Checked exceptions are exceptions that are checked at compile-time. If your
code throws a checked exception, the compiler ensures that you either handle the exception
using a try-catch block or declare it using the throws keyword in the method signature.
 Examples:
o IOException: When dealing with input/output operations.
o SQLException: When accessing a database.
o ClassNotFoundException: When a class cannot be found during class loading.
 Handling: The developer is required to handle checked exceptions, making the program
more robust. Failure to handle them results in a compile-time error.
Example:
import java.io.*;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream("nonexistentfile.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
2. Unchecked Exceptions
 Definition: Unchecked exceptions are exceptions that are not checked at compile-time,
meaning the compiler doesn’t force you to handle them. These exceptions are usually the
result of logical errors in your program, like accessing invalid data or performing incorrect
operations.
 Examples:
o NullPointerException: When you try to access an object with a null reference.
o ArrayIndexOutOfBoundsException: When you try to access an array with an
illegal index.
o ArithmeticException: When an illegal arithmetic operation (e.g., division by zero)
occurs.
o IllegalArgumentException: When a method receives an inappropriate argument.
 Handling: Unchecked exceptions do not need to be declared or handled explicitly, but it’s
good practice to handle them in order to make the program more robust and avoid runtime
crashes.
Example:
public class UncheckedExceptionExample {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // Throws ArrayIndexOutOfBoundsException
}
}
Key Differences:
Feature Checked Exception Unchecked Exception
Compile-time Checked by the compiler Not checked by the compiler
checking
Handling Must be handled (try-catch Not mandatory to handle
requirement or throws)
Examples IOException, NullPointerException,
SQLException, etc. ArithmeticException
Error type Often due to external Usually due to programming
conditions (e.g., I/O) errors (e.g., logic)

You might also like