Unit 4
Unit 4
2. 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.
These packages consist of many classes which are a part of Java API.Some of the
commonly usedbuilt-inpackagesare:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types,mathoperations).Thispackageisautomaticallyimported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.2) Java package provides access protection.3) Java package removes naming
collision.
There are three ways to access the package from outside the package.
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 subpackages.
The import keyword is used to make the classes and interface of another package accessible
to the current package.
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();
7. obj.msg();
8. }
9. }
S. No. PATH CLASSPATH
Packages in java SE
The SE stands for Java Standard Edition is a computing platform in which we can
execute software, and it can be used for development and deployment of portable code for
desktop and server environments.
It is the core Java programming platform and provides all the libraries and APIs such
as java.lang, java.io, java.math, java.net, java.util etc.
To create an enum, use the enum keyword (instead of class or interface), and separate
the constants with a comma. Note that they should be in uppercase letters:
Java Enums can be thought of as classes which have a fixed set of constants (a
variable that does not change). The Java enum constants are static and final implicitly. It is
available since JDK 1.5.
Enums are used to create our own data type like classes. The enum data type (also
known as Enumerated Data Type) is used to define an enum in Java
Java Math class: Java Math class provides several methods to work on math calculations
like min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
1. public class JavaMathExample1
2. {
3. public static void main(String[] args)
4. {
5. double x = 28;
6. double y = 4;
7. // return the maximum of two numbers
8. System.out.println("Maximum number of x and y is: " +Math.max(x, y));
9. // return the square root of y
10. System.out.println("Square root of y is: " + Math.sqrt(y));
11. //returns 28 power of 4 i.e. 28*28*28*28
12. System.out.println("Power of x and y is: " + Math.pow(x, y));
13. // return the logarithm of given value
14. System.out.println("Logarithm of x is: " + Math.log(x));
15. System.out.println("Logarithm of y is: " + Math.log(y));
16. // return the logarithm of given value when base is 10
17. System.out.println("log10 of x is: " + Math.log10(x));
18. System.out.println("log10 of y is: " + Math.log10(y));
19. // return the log of x + 1
20. System.out.println("log1p of x is: " +Math.log1p(x));
21. // return a power of 2
22. System.out.println("exp of a is: " +Math.exp(x));
23. // return (a power of 2)-1
24. System.out.println("expm1 of a is: " +Math.expm1(x));
25. }
Wrapper classes
The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Autoboxing: The automatic conversion of primitive data type into its corresponding wrapper
class is known as autoboxing, for example, byte to Byte, char to Character, int to Integer,
long to Long, float to Float, boolean to Boolean, double to Double, and short to Short.
Class Description
Formatter class
The java.util.Formatter class provides support for layout justification and alignment, common
formats for numeric, string, and date/time data, and locale-specific output.
1 Formatter()
This constructor constructs a new formatter.
Formatter(Appendable a)
2 This constructor constructs a new formatter with the specified
destination.
Formatter(Appendable a, Locale l)
3 This constructor constructs a new formatter with the specified destination
and locale.
4 Formatter(File file)
This constructor constructs a new formatter with the specified file.
7 Formatter(Locale l)
This constructor constructs a new formatter with the specified locale.
Formatter(OutputStream os)
8 This constructor constructs a new formatter with the specified output
stream.
Formatter(PrintStream ps)
11 This constructor constructs a new formatter with the specified print
stream.
12 Formatter(String fileName)
This constructor constructs a new formatter with the specified file name.
Class methods
void close()
1
This method closes this formatter.
void flush()
2
This method flushes this formatter.
IOException ioException()
5
This method returns the IOException last thrown by this formatter's
Appendable.
Locale locale()
6
This method returns the locale set by the construction of this formatter.
Appendable out()
7
This method returns the destination for the output.
String toString()
8
This method returns the result of invoking toString() on the destination for the
output.
Java Random class: Java Random class is used to generate a stream of pseudorandom
numbers. The algorithms implemented by Random class use a protected utility method than
can supply up to 32 pseudorandomly generated bits on each invocation.
Methods
Methods Description
nextBoolean() Returns the next uniformly distributed pseudorandom boolean value from the
random number generator's sequence
nextByte() Generates random bytes and puts them into a specified byte array.
nextDouble() Returns the next pseudorandom Double value between 0.0 and 1.0 from the
random number generator's sequence
nextFloat() Returns the next uniformly distributed pseudorandom Float value between 0.0
and 1.0 from this random number generator's sequence
nextGaussian( Returns the next pseudorandom Gaussian double value with mean 0.0 and
) standard deviation 1.0 from this random number generator's sequence.
nextInt() Returns a uniformly distributed pseudorandom int value generated from this
random number generator's sequence
nextLong() Returns the next uniformly distributed pseudorandom long value from the
random number generator's sequence.
setSeed() Sets the seed of this random number generator using a single long seed.
Example:
1. import java.util.Random;
2. public class JavaRandomExample2 {
3. public static void main(String[] args) {
4. Random random = new Random();
5. //return the next pseudorandom integer value
6. System.out.println("Random Integer value : "+random.nextInt());
7. // setting seed
8. long seed =20;
9. random.setSeed(seed);
10. //value after setting seed
11. System.out.println("Seed value : "+random.nextInt());
12. //return the next pseudorandom long value
13. Long val = random.nextLong();
14. System.out.println("Random Long value : "+val);
15. }
16. }
Time package
Java Dates
Java does not have a built-in Date class, but we can import the java.time package to work
with the date and time API. The package includes many date and time classes. For example:
Class Description
To display the current date, import the java.time.LocalDate class, and use its now() method:
To display the current time (hour, minute, second, and nanoseconds), import
the java.time.LocalTime class, and use its now() method:
Example
System.out.println(myObj);
To display the current date and time, import the java.time.LocalDateTime class, and use
its now() method:
Example
System.out.println(myObj);
Method Description
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited
by two subclasses: Exception and Error. The hierarchy of Java Exception classes is
given below:
Java provides five keywords that are used to handle the exception. The following table
describes each.
Keywor Description
d
try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
There are given some scenarios where unchecked exceptions may occur. They are as follows:
1. int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may
be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following
statements.
TestThrows.java
Let's see the below example where the Java code throws an exception and the catch block
handles that exception. Later the finally block is executed after the try-catch block. Further,
the rest of the code is also executed normally.
FinallyExample.java
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
1. If SuperClass doesn’t declare any exception and subclass declare checked exception.
class SuperClass {
System.out.println("SubClass");
}
// Driver code
public static void main(String args[]) {
SuperClass s = new SubClass();
s.method();
}
}
Java Custom Exception :In Java, we can create our own exceptions that are derived classes
of the Exception class. Creating our own Exception is known as custom exception or user-
defined exception. Basically, Java custom exceptions are used to customize the exception
according to user need.
1. // class representing custom exception
2. class InvalidAgeException extends Exception
3. {
4. public InvalidAgeException (String str)
5. {
6. // calling the constructor of parent Exception
7. super(str);
8. }
9. }
10.
11. // class that uses custom exception InvalidAgeException
12. public class TestCustomException1
13. {
14.
15. // method to check the age
16. static void validate (int age) throws InvalidAgeException{
17. if(age < 18){
18.
19. // throw an object of user defined exception
20. throw new InvalidAgeException("age is not valid to vote");
21. }
22. else {
23. System.out.println("welcome to vote");
24. }
25. }
26.
27. // main method
28. public static void main(String args[])
29. {
30. try
31. {
32. // calling the method
33. validate(13);
34. }
35. catch (InvalidAgeException ex)
36. {
37. System.out.println("Caught the exception");
38.
39. // printing the message from InvalidAgeException object
40. System.out.println("Exception occured: " + ex);
41. }
42.
43. System.out.println("rest of the code...");
44. }
45. }
Java Nested try block
In Java, using a try block inside another try block is permitted. It is called as nested try block.
Every statement that we enter a statement in try block, context of that exception is pushed
onto the stack.
Syntax:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....
NestedTryBlock.java
An exception can be rethrown in a catch block using throw keyword, if catch block is unable
to handle it. This process is called as re-throwing an exception.