OOPJ(java) Unit-IV
OOPJ(java) Unit-IV
Packages and Java Library , Exception Handling , Java I/O and File
a)Introduction:
b) Defining Package :
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
package mypack; (//save by B.java )
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:
Hello
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:
Hello
package myPackage;
import java.util.*;
public class ImportingExample
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
int i = read.nextInt();
System.out.println("You have entered a number " + i);
Random rand = new Random();
int num = rand.nextInt(100);
System.out.println("Randomly generated number " + num);
}
}
In the above code, the class ImportingExample belongs to myPackage package, and it also importing all the
classes like Scanner, Random, Stack, Vector, ArrayList, HashSet, etc. from the java.util package.
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when you
are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
Example (//save by A.java )
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
package mypack; (//save by B.java )
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output: Hello
1. An environment variable is used by the operating An environment variable is used by the Java
system to find the executable files. compiler to find the path of classes.
2. PATH setting up an environment for the operating Classpath setting up the environment for Java.
system. OS will look in this PATH for executables. Java will use to find compiled classes.
In java, the access modifiers define the accessibility(visibility) of the class and its members.
Java has four access modifiers, and they are default, private, protected, and public.
The class acts as a container of data and methods. So, the access modifier decides the accessibility of
class members across the different packages.
User-defined Packages
The user-defined packages are the packages created by the user. User is free to create their own packages.
b) Java.lang Package and its Classes
Following is the list of important classes in java.lang.package:
Boolean − The Boolean class wraps a value of the primitive type boolean in an object. An object of type
Boolean contains a single field whose type is boolean.
Byte − The Byte class class wraps a value of primitive type byte in an object. An object of type Byte
contains a single field whose type is byte.
Character − The Character class offers a number of useful class (i.e., static) methods for manipulating
characters.
Compiler − The Compiler class is provided to support Java-to-native-code compilers and related services.
By design, it serves as a placeholder for a JIT compiler implementation.
Double − The Double class wraps a value of primitive type double in an object. An object of type Double
contains a single field whose type is double.
Enum − The Enum class is the common base class of all Java language enumeration types.
Float − The Float class wraps a value of primitive type float in an object. An object of type Float contains a
single field whose type is float.
Integer − The Integer class wraps a value of primitive type int in an object. An object of type Integer
contains a single field whose type is int.
Example
enum WeekDay
{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
All WeekDays:
MONDAY
TUESDAY
WEDNESSDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
The ordinal() method of Enum class returns the ordinal of this enumeration constant.
This method is designed to be used by sophisticated enum-based data structures, like EnumSet and EnumMap.
Syntax
public final int ordinal()
Return Value
The ordinal() method returns this enumeration constant's ordinal.
Example
public class Enum_ordinalMethodExample1
{
enum Colours
{
Red,Green,Brown,Yellow;
}
Output:
Red ordinal = 0
Green Ordinal = 1
Brown Ordinal = 2
Yellow Ordinal = 3
c) class Math
Java Math Methods
The java.lang.Math class contains various methods for performing basic numeric operations such as the
logarithm, cube root, and trigonometric functions etc. The various java math methods are as follows:
Method Description
Math.pow() It returns the value of first argument raised to the power to second argument.
Method Description
Math.sin() It is used to return the trigonometric Sine value of a Given double value.
Math.cos() It is used to return the trigonometric Cosine value of a Given double value.
Math.tan() It is used to return the trigonometric Tangent value of a Given double value.
Math.asin() It is used to return the trigonometric Arc Sine value of a Given double value
Math.acos() It is used to return the trigonometric Arc Cosine value of a Given double value.
Math.atan() It is used to return the trigonometric Arc Tangent value of a Given double value.
Example:
public class JavaMathExample1
{
public static void main(String[] args)
{
double x = 28;
double y = 4;
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java JavaMathExample1
Maximum number of x and y is: 28.0
Square root of y is: 2.0
Power of x and y is: 614656.0
Logarithm of x is: 3.332204510175204
Logarithm of y is: 1.3862943611198906
log10 of x is: 1.4471580313422192
log10 of y is: 0.6020599913279624
Output:
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
Interface Description
Comparator<T> A comparison function, which imposes a total ordering on some collection of objects.
Deque<E> A linear collection that supports element insertion and removal at both ends.
Enumeration<E> An object that implements the Enumeration interface generates a series of elements, one at a
time.
EventListener A tagging interface that all event listener interfaces must extend.
Formattable The Formattable interface must be implemented by any class that needs to perform custom
formatting using the 's' conversion specifier of Formatter.
Iterator<E> An iterator over a collection.
ListIterator<E> An iterator for lists that allows the programmer to traverse the list in either direction, modify
the list during iteration, and obtain the iterator's current position in the list.
Map<K,V> An object that maps keys to values.
Class Description
AbstractList<E> This class provides a skeletal implementation of the List interface to minimize the effort
required to implement this interface backed by a "random access" data store (such as an
array).
AbstractMap<K,V> This class provides a skeletal implementation of the Map interface, to
minimize the effort required to implement this interface.
Arrays This class contains various methods for manipulating arrays (such as
sorting and searching).
Calendar The Calendar class is an abstract class that provides methods for converting between a
specific instant in time and a set of calendar fields such
as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the
calendar fields, such as getting the date of the next week.
Collections This class consists exclusively of static methods that operate on or return
collections.
Date The class Date represents a specific instant in time, with millisecond
precision.
Scanner A simple text scanner which can parse primitive types and strings using
regular expressions.
// setting seed
}
Output:
D:\ACEM\II AI DS>javac JavaRandomExample.java
D:\ACEM\II AI DS>java JavaRandomExample
Random Integer value : -1652727993
Seed value : -1150867590
Random Long value : -7322354119883315205
Class Summary
Class Description
Clock A clock providing access to the current instant, date and time using a time-zone.
LocalDate A date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03.
LocalDateTime A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.
LocalTime A time without a time-zone in the ISO-8601 calendar system, such as 10:15:30.
Example:
import java.time.LocalDate;
public class LocalDateExample1
{
public static void main(String[] args)
{
LocalDate date = LocalDate.now();
Output:
2017-01
Method Description
isAfter(Instant otherInstant) This method checks if this instant is after the specified instant.
isBefore(Instant otherInstant) This method checks if this instant is before the specified instant.
minus(long amountToSubtract, This method returns a copy of this instant with the specified amount
TemporalUnit unit) subtracted.
now() This method obtains the current instant from the system clock.
until(Temporal endExclusive, This method calculates the amount of time until another instant in terms
TemporalUnit unit) of the specified unit.
Example:
import java.time.*;
public class InstantExample
{
public static void main(String[] args)
{
Instant cur = Instant.now();
System.out.println("Current Instant is " + cur);
System.out.println("Instant after subtraction : "+ diff); // Using plus()to find instant value after addition
import java.time.format.DateTimeFormatter;
import java.time.LocalDate;
import java.util.Formatter;
import java.text.Format;
class TimeFormats
{
public static void main(String args[])
{
LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);
System.out.println(parsedDate );
}
}
Output: D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java TimeFormats
2024-09-20
Object Oriented Programming Through Java Page 23
4.11 Temporal Adjusters Class
TemporalAdjusters Class in Java provides Adjusters, which are a key tool for modifying temporal
objects.
Examples include an adjuster that sets the date like “Second Saturday of the Month” or “Next
Tuesday”, or one that sets the date to the last day of the month.
TemporalAdjuster can be used in two ways.
The first is by invoking the method on the interface directly. The second is by using
Temporal.with(TemporalAdjuster):
The following two ways of using TemporalAdjuster are equivalent, but it is recommended to use the
second approach, as it is cleaner and readable
temporal = thisAdjuster.adjustInto(temporal);
temporal = temporal.with(thisAdjuster);
Methods
Method Description
This method is used to return the “first day of next month” adjuster,
firstDayOfNextMonth()
which returns a new date set to the first day of the next month.
This method is used to return the “first day of next year” adjuster,
firstDayOfNextYear()
which returns a new date set to the first day of the next year.
This method is used to return the “first day of year” adjuster, which
firstDayOfYear()
returns a new date set to the first day of the current year.
This method is used to return the “last day of month” adjuster, which
lastDayOfMonth()
returns a new date set to the last day of the current month.
This method is used to return the “last day of year” adjuster, which
lastDayOfYear()
returns a new date set to the last day of the current year.
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java TemporalAdjusterExample
Today's date is: 2024-09-22
Next Monday is on : 2024-09-23
import java.io.IOException;
class Testthrows1
{
void m() throws IOException
{
throw new IOException("device error"); //checked exception
}
void n() throws IOException
{
m();
}
void p()
{
try
{
n();
}
catch(Exception e)
{
System.out.println("exception handled");
}
}
1. Definition throw keyword is used throw an Java throws keyword is used in the method
exception explicitly from inside the signature.
function .
2. Type of Using throw keyword, we can only Using throws keyword, we can declare both
exception propagate unchecked exception i.e., the checked and unchecked exceptions. However,
checked exception cannot be propagated the throws keyword can be used to propagate
using throw only. checked exceptions only.
3. Syntax The throw keyword is followed by an The throws keyword is followed by class
instance of Exception to be thrown. names of Exceptions to be thrown.
4. Declaration throw is used within the method. throws is used with the method signature.
Note:
If you don't handle the exception, before terminating the program, JVM executes finally block (if any).
Why use Java finally block?
finally block in Java can be used to put "cleanup" code such as closing a file, closing connection, etc.
Uses:
Case 1: When an exception does not occur
Case 2: When an exception occurs but not handled by the catch block
Case 3: When an exception occurs and is handled by the catch block
The code throws an exception however the catch block cannot handle it.
Even though, the finally block is executed after the try block and then the program terminates abnormally.
TestFinallyBlock1.java
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data = 25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
Example where the Java code throws an exception and the catch block handles the exception.
Later the finally block is executed after the try-catch block.
Further, the rest of the code is also executed normally.
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data = 25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(" Exception handled ");
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
D:\ACEM\II CSE Bsection>javac TestFinallyBlock.java
D:\ACEM\II CSE Bsection>java TestFinallyBlock
Exception handled
finally block is always executed
rest of the code...
Note:
For each try block there can be zero or more catch blocks, but only one finally block.
The finally block will not be executed if the program exits ( by calling System.exit())
Example 1 MultipleCatchBlock1.java
public class MultipleCatchBlock1
{
public static void main(String[] args)
{
try
{
int a[] = new int[5];
a[5] = 30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output: Arithmetic Exception occurs
rest of the code
Unchecked Exception
2. User-Defined Exceptions
1. These exceptions are checked at compile time. These exceptions are just opposite to the checked
These exceptions are handled at compile time too. exceptions. These exceptions are not checked and
handled at compile time.
2. These exceptions are direct subclasses of They are the direct subclasses of the
Exception RuntimeException class.
4. These exceptions are propagated using the throws These are automatically propagated.
keyword
5. It is required to provide the try-catch and try- In the case of unchecked exception it is not
finally block to handle the checked exception. mandatory.
S. Example
No. Exception Class with Description
Checked Exceptions:
ClassNotFoundException
IOException
SQLException
InterruptedException
FileNotFoundException
OutputStream class
The OutputStream class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.
S.No. Method with Description
1 void write(int n)
It writes byte(contained in an int) to the output stream.
2 void write(byte[] b)
It writes a whole byte array(b) to the output stream.
3 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
4 void close()
It closes the output stream and also frees any resources connected with this output stream.
Reader class
The Reader class has defined as an abstract class, and it has the following methods which have implemented by
its concrete classes.
S.No. Method with Description
1 int read()
It reads the next character from the input stream.
2 String readLine()
It reads a line of text. A line is considered to be terminated by any one of a line feed ('\n')
a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
3 boolean ready()
It tells whether the stream is ready to be read.
4 void close()
It closes the input stream and also frees any resources connected with this input stream.
Writer class
The Writer class has defined as an abstract class, and it has the following methods which have implemented by
its concrete classes.
Method Description
int nextInt() It is used to scan the next token of the input as an integer.
float nextFloat() It is used to scan the next token of the input as a float.
double nextDouble() It is used to scan the next token of the input as a double.
byte nextByte() It is used to scan the next token of the input as a byte.
boolean nextBoolean() It is used to scan the next token of the input into a boolean value.
long nextLong() It is used to scan the next token of the input as a long.
short nextShort() It is used to scan the next token of the input as a Short.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReadingTest1
{
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try
{
in = new FileReader("D:\\ACEM\\II AI DS\\Input-File1.txt");
out = new FileWriter("D:\\ACEM\\II AI DS\\Output-File1.txt");
int c;