2. PACKAGES
◼ 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.
◼ Here, we will have the detailed learning of creating and using user-defined packages.
3. PACKAGES
◼ Advantages of using java packages
◼ 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.
6. PACKAGES
◼ How to access package from another package?
◼ There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
7. PACKAGES
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.
Example of package that import the packagename.*
8. PACKAGES
2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
Example of package by import package.classname
9. PACKAGES
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.
Example of package by import fully qualified name
10. PACKAGES
Java packages API
The Java API is a library of prewritten classes, that are free to use, included in the Java Development
Environment.
The library contains components for managing input, database programming, and much more. The
complete list can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/.
The library is divided into packages and classes. Meaning you can either import a single class (along with
its methods and attributes), or a whole package that contain all the classes that belong to the specified
package.
To use a class or a package from the library, you need to use the import keyword:
12. PACKAGES
◼ Import a Class
If you find a class you want to use, for example, the Scanner class, which is used
to get user input, write the following code:
In the example above, java.util is a package, while Scanner is a class of the
java.util package.
To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation. In our example,
we will use the nextLine() method, which is used to read a complete line:
14. JAVA NAMING CONVENTIONS
◼ Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package,
variable, constant, method, etc.
◼ But, it is not forced to follow. So, it is known as convention not rule. These conventions are suggested by several
Java communities such as Sun Microsystems and Netscape.
◼ All the classes, interfaces, packages, methods and fields of Java programming language are given according to the
Java naming convention. If you fail to follow these conventions, it may generate confusion or erroneous code.
15. JAVA NAMING CONVENTIONS
◼ Advantage of Naming Conventions in Java
◼ By using standard Java naming conventions, you make your code easier to read for yourself and other
programmers. Readability of Java program is very important. It indicates that less time is spent to figure out what
the code does.
18. CREATING A PACKAGE IN JAVA
◼ How to Create Package in Java
◼ In Java, a package is a group of classes, interfaces, enumeration, and annotations. Java contains many pre-defined
packages such as java.lang, java.io, java.net, etc. When we create any Java program the java.lang package is
imported by default. We need not to write the package name at the top of the program. We can also create
our own package by providing the name that we want. In this section, we will learn how to create a package
in Java.
19. CREATING A PACKAGE IN JAVA
◼ Creating a Package
◼ To create a package, follow the steps given below:
• Choose a package name according to the naming convention.
• Write the package name at the top of every source file (classes, interface, enumeration, and annotations).
• Remember that there must be only one package statement in each source file.
20. HIDDEN CLASSES
◼ Hidden classes are classes that cannot be used directly by the bytecode or other classes. Even
though it’s mentioned as a class, it should be understood to mean either a hidden class or interface. It can also be
defined as a member of the access control nest and can be unloaded independently of other classes.
21. HIDDEN CLASSES
◼ Properties of Hidden Classes
◼ Let’s take a look at the properties of these dynamically generated classes:
• Non-discoverable – a hidden class is not discoverable by the JVM during bytecode linkage, nor by programs making
explicit use of class loaders. The reflective methods Class::forName, ClassLoader::findLoadedClass,
and Lookup::findClass will not find them.
• We can’t use the hidden class as a superclass, field type, return type, or parameter type.
• Code in the hidden class can use it directly, without relying on the class object.
• final fields declared in hidden classes are not modifiable regardless of their accessible flags.
22. HIDDEN CLASSES
Creating Hidden Classes
◼ The hidden class isn’t created by any class loader. It has the same defining class loader, runtime package, and
protection domain of the lookup class.
◼ First, let’s create a Lookup object:
◼ MethodHandles.Lookup lookup = MethodHandles.lookup();
◼ Copy
◼ The Lookup::defineHiddenClass method creates the hidden class. This method accepts an array of bytes.
◼ For simplicity, we’ll define a simple class with the name HiddenClass that has a method to convert a given string
to uppercase:
25. MULTI THREADED PROGRAMMING IN JAVA - INTRODUCTION
◼ Multithreading in Java is a process of executing multiple threads simultaneously.
◼ A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are
used to achieve multitasking.
◼ However, we use multithreading than multiprocessing because threads use a shared memory area. They don't
allocate separate memory area so saves memory, and context-switching between the threads takes less time than
process.
◼ Java Multithreading is mostly used in games, animation, etc.
26. MULTI THREADED PROGRAMMING IN JAVA - INTRODUCTION
◼ Advantages of Java Multithreading
◼ 1) It doesn't block the user because threads are independent and you can perform multiple operations at the
same time.
◼ 2) You can perform many operations together, so it saves time.
◼ 3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
27. MULTI THREADED PROGRAMMING IN JAVA - INTRODUCTION
◼ Multitasking
◼ Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved in two ways:
• Process-based Multitasking (Multiprocessing)
• Thread-based Multitasking (Multithreading)
28. MULTI THREADED PROGRAMMING IN JAVA - INTRODUCTION
◼ 1) Process-based Multitasking (Multiprocessing)
• Each process has an address in memory. In other words, each process allocates a separate memory area.
• A process is heavyweight.
• Cost of communication between the process is high.
• Switching from one process to another requires some time for saving and loading registers, memory maps,
updating lists, etc.
29. MULTI THREADED PROGRAMMING IN JAVA - INTRODUCTION
◼ 2) Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is low.
30. THREAD IN JAVA
◼ A thread is a lightweight subprocess,
the smallest unit of processing. It is a
separate path of execution.
◼ Threads are independent. If there
occurs exception in one thread, it
doesn't affect other threads. It uses a
shared memory area.
As shown in the figure, a thread is
executed inside the process. There is
context-switching between the threads.
There can be multiple processes inside
the OS, and one process can have multiple
threads.
31. THREAD IN JAVA
◼ Java Thread class
◼ Java provides Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable interface.
38. CREATING A THREAD IN JAVA
◼ Using the thread class : Thread(String Name)
39. CREATING A THREAD IN JAVA
◼ Using the thread class : Thread(String Name)
40. CREATING A THREAD IN JAVA
◼ Using the thread class : Thread(String Name)
41. THREAD STOP() MOTHOD
◼ The stop() method of thread class terminates the thread execution. Once a thread is stopped, it
cannot be restarted by start() method.
Parameter
obj : The Throwable object to be thrown.
Return
This method does not return any value.
Exception
SecurityException: This exception throws if the current thread cannot modify the thread.
43. LIFE CYCLE OF A THREAD
Life cycle of a Thread (Thread States)
In Java, a thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
45. LIFE CYCLE OF A THREAD
◼ New: Whenever a new thread is created, it is always in the new state. For a thread in the new state, the code has
not been run yet and thus has not begun its execution.
◼ Active: When a thread invokes the start() method, it moves from the new state to the active state. The active state
contains two states within it: one is runnable, and the other is running.
◼ Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state, the thread may
be running or may be ready to run at any given instant of time. It is the duty of the thread scheduler to provide the
thread time to run, i.e., moving the thread the running state.
◼ Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally, the most
common change in the state of a thread is from runnable to running and again back to runnable.
46. LIFE CYCLE OF A THREAD
◼ Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either the thread is in
the blocked state or is in the waiting state.
◼ Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A) has entered the
critical section of a code and is not willing to leave that critical section. In such a scenario, another thread (its name is
B) has to wait forever, which leads to starvation. To avoid such scenario, a timed waiting state is given to thread B.
Thus, thread lies in the waiting state for a specific span of time, and not forever. A real example of timed waiting is
when we invoke the sleep() method on a specific thread. The sleep() method puts the thread in the timed wait state.
After the time runs out, the thread wakes up and start its execution from when it has left earlier.
◼ Terminated: A thread reaches the termination state because of the following reasons:
• When a thread has finished its job, then it exists or terminates normally.
• Abnormal termination: It occurs when some unusual events such as an unhandled exception or segmentation fault.
◼ A terminated thread means the thread is no more in the system. In other words, the thread is dead, and there is no way
one can respawn (active after kill) the dead thread.
47. LIFE CYCLE OF A THREAD
Implementation of Thread States
◼ In Java, one can get the current state of a thread using the Thread.getState() method.
The java.lang.Thread.State class of Java provides the constants ENUM to represent the state of a thread. These
constants are:
49. THREAD EXCEPTIONS
◼ Thread Exception in Java | When we call a sleep() method in a Java program, it must be enclosed in
try block and followed by catch block.
◼ This is because sleep() method throws an exception named InterruptedException that should be caught.
If we fail to catch this exception, the program will not compile.
◼ JVM (Java Runtime System) will throw an exception named IllegalThreadStateException whenever we
attempt to call a method that a thread cannot handle in the given state.
◼ For example, a thread that is in a sleeping state cannot deal with the resume() method because a
sleeping thread cannot accept instructions. The same thing is true for the suspend() method when it is
used on a blocked thread.
◼ When we call a thread method that may throw an exception, we will have to use an appropriate
exception handler to catch it. The catch block may take one of the following forms:
51. THREAD EXCEPTIONS
◼ Exceptions in Main Thread
◼ 1. Exception in thread main java.lang.UnsupportedClassVersionError: This exception occurs in a program
when a java class is compiled from another JDK version and we are trying to run it from another java version.
The UnsupportedClassVersionError is present java.lang package.
◼ 2. Exception in thread main java.lang.NoClassDefFoundError: This exception occurs in two flavors. The first
scenario is where we provide class full name with .class extension. The second scenario comes when Class is
not found.
◼ 3. Exception in thread main java.lang.NoSuchMethodError: main: This exception occurs in a Java program
when a class is trying to run without the main method declaration.
◼ 4. Exception in thread main java.lang.ArithmeticException: When any exception is thrown from main
method, it prints the exception in the console.
◼ The first part explains that exception is thrown from the main method, second part prints the exception class
name and then after a colon, it prints an exception message.
52. PRIORITY OF THREAD
◼ Each thread has a priority. Priorities are represented by a number between 1 and 10.
◼ In most cases, the thread scheduler schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.
Note that not only JVM a Java programmer can also assign the priorities of a thread explicitly in a Java program.
53. PRIORITY OF THREAD
◼ Setter & Getter Method of Thread Priority
◼ Let's discuss the setter and getter method of the thread priority.
◼ public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of the given thread.
◼ public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or assign the
priority of the thread to newPriority. The method throws IllegalArgumentException if the value newPriority goes
out of the range, which is 1 (minimum) to 10 (maximum).
54. PRIORITY OF THREAD
◼ 3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
57. SYNCHRONIZATION IN JAVA
◼ Synchronization in Java is the capability to control the access of multiple threads to any shared resource.
◼ Java Synchronization is better option where we want to allow only one thread to access the shared resource.
58. SYNCHRONIZATION IN JAVA
◼ Why use Synchronization?
◼ The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
59. SYNCHRONIZATION IN JAVA
◼ Types of Synchronization
◼ There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
◼ Here, we will discuss only thread synchronization.
60. SYNCHRONIZATION IN JAVA
◼ Java Synchronized Method
◼ If you declare any method as synchronized, it is known as synchronized method.
◼ Synchronized method is used to lock an object for any shared resource.
◼ When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it
when the thread completes its task.
63. JAVA RUNNABLE INTERFACE
◼ Java runnable is an interface used to execute code on a concurrent thread. It is an interface which is implemented
by any class if we want that the instances of that class should be executed by a thread.
◼ The runnable interface has an undefined method run() with void as return type, and it takes in no arguments. The
method summary of the run() method is given below-
64. JAVA RUNNABLE INTERFACE
◼ The runnable interface provides a standard set of rules for the instances of classes which wish to execute code
when they are active. The most common use case of the Runnable interface is when we want only to override the
run method. When a thread is started by the object of any class which is implementing Runnable, then it invokes
the run method in the separately executing thread.
65. JAVA RUNNABLE INTERFACE
◼ Implementing Runnable
◼ It is the easiest way to create a thread by implementing Runnable. One can create a thread on any object by
implementing Runnable. To implement a Runnable, one has only to implement the run method.
◼ public void run()
◼ In this method, we have the code which we want to execute on a concurrent thread. In this method, we can use
variables, instantiate classes, and perform an action like the same way the main thread does. The thread remains
until the return of this method. The run method establishes an entry point to a new thread.
66. JAVA RUNNABLE INTERFACE
◼ How to create a thread using Runnable interface
◼ To create a thread using runnable, use the following code
69. EXCEPTION HANDLING IN JAVA
◼ The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the
normal flow of the application can be maintained.
◼ What is Exception in Java?
◼ Exception is an abnormal condition.
◼ In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at
runtime.
70. EXCEPTION HANDLING IN JAVA
◼ Advantage of Exception Handling
◼ The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application; that is why we need to handle exceptions.
Let's consider a scenario:
◼ Suppose there are 10 statements in a Java program and an
exception occurs at statement 5; the rest of the code will not be
executed, i.e., statements 6 to 10 will not be executed. However,
when we perform exception handling, the rest of the statements
will be executed. That is why we use exception handling in Java.
71. EXCEPTION HANDLING IN JAVA
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:
Hierarchy of Java Exception classes
72. EXCEPTION HANDLING IN JAVA
◼ Types of Java Exceptions
◼ There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are three
types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
73. EXCEPTION HANDLING IN JAVA
1) Checked Exception
◼ The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked
exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
◼ The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime.
3) Error
◼ Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.
74. EXCEPTION HANDLING IN JAVA
◼ Java Exception Keywords
◼ Java provides five keywords that are used to handle the exception. The following table describes each.
76. EXCEPTION HANDLING IN JAVA
◼ Common Scenarios of Java Exceptions
1) A scenario where ArithmeticException occurs
◼ If we divide any number by zero, there occurs an 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.
77. EXCEPTION HANDLING IN JAVA
◼ Common Scenarios of Java Exceptions
3) A scenario where NumberFormatException occurs
◼ If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we
have a string variable that has characters; converting this variable into digit will cause 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.
78. MULTIPLE CATCH BLOCK
◼ Java Multi-catch block
◼ A try block can be followed by one or more catch blocks. Each catch block must contain a different exception
handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java
multi-catch block.
• At a time only one exception occurs and at a time only one catch block is executed.
• All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must
come before catch for Exception.
81. FINALLY BLOCK
◼ Java finally block is a block used to execute important code such as closing the connection, etc.
◼ Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the
necessary statements that need to be printed regardless of the exception occurs or not.
◼ The finally block follows the try-catch block.
Flowchart of finally block
82. FINALLY BLOCK
Why use Java finally block?
• finally block in Java can be used to put "cleanup" code such as closing a file, closing connection, etc.
• The important statements to be printed can be placed in the finally block.
84. THROWING OUR OWN EXCEPTIONS (USER DEFINED)
◼ Java throw Exception
◼ In Java, exceptions allows us to write good quality codes where the errors are checked at the compile time instead
of runtime and we can create custom exceptions making the code recovery and debugging easier.
◼ Java throw keyword
◼ The Java throw keyword is used to throw an exception explicitly.
◼ We specify the exception object which is to be thrown. The Exception has some message with it that provides the
error description. These exceptions may be related to user inputs, server, etc.
85. THROWING OUR OWN EXCEPTIONS (USER DEFINED)
◼ Java throw Exception
◼ In Java, exceptions allows us to write good quality codes where the errors are checked at the compile time instead
of runtime and we can create custom exceptions making the code recovery and debugging easier.
◼ Java throw keyword
◼ The Java throw keyword is used to throw an exception explicitly.
◼ We specify the exception object which is to be thrown. The Exception has some message with it that provides the
error description. These exceptions may be related to user inputs, server, etc.