Java Packages and Access Modifiers Guide
Java Packages and Access Modifiers Guide
Package,
Multithreading,
Exception
Handling
Packag
□A package as the es
name suggests is a pack(group) of
classes, interfaces and other packages. In java we use
packages to organize our classes and interfaces.
□A package in Java is used to group related classes.
Think of it as a folder in a file directory. We use
packages to avoid name conflicts, and to write a better
maintainable code. Packages are divided into two
categories:
✔Built-in Packages (packages from the Java API)
✔User-defined Packages (create your own packages)
Packag
□ Packages-Built-in Packages es
(packages from the Java 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 much more.
✔ 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:
Packag
Syntax
es
import [Link]; // Import a single
class import [Link].*; // Import the
whole package
Example:
□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:
import [Link];
Example
Using the Scanner class to get user
input: import [Link];
class MyClass {
public static void main(String[] args) {
Scanner myObj = new
Scanner([Link]);
[Link]("Enter
username");
String userName = [Link]();
[Link]("Username is: " +
userName);
}
}
Packag
□ Import a
Package
✔
es
There are many packages to choose from. In the previous example, we used the Scanner class from the [Link] package. This package
also contains date and time facilities, random-number generator and other utility classes.
✔ To import a whole package, end the sentence with an asterisk sign (*). The following example will import ALL the classes in
the [Link] package:
Syntax:
import [Link].*;
Example:
import [Link].*;
// import the [Link]
package
class MyClass {
public static void main(String[] args)
{ Scanner myObj = new
Scanner([Link]); String userName;
//save by //save by
[Link] [Link]
package pack; package
public class A{ mypack;
public void msg() import
class B{pack.A;
{ public static void main(String
[Link]("Hello args[])
");} {
} A obj = new
A();
[Link]();
}
}
How to access package from another
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. [Link] and [Link] packages contain Date class.
Example of package by import fully qualified name
//save by //save by [Link]
[Link] package mypack;
package class B
pack; public {
class Avoid msg() public static void main(String
public
{ args[])
{[Link]("Hello
{
");}
pack.A obj = new pack.A();//using
}
fully q ualified name
Output: Hello [Link]();
}
Access
□ There are Modifier
two types of modifiers
in java:
access modifiers and non-access modifiers.
□ The access modifiers in java specifies accessibility
(scope) of a data member, method, constructor or
class.
□ There are 4 types of java access modifiers:
✔ Private
✔ Default
✔ Protected
✔ public
□ There are many non-access modifiers such as
static, abstract, synchronized, native, volatile,
transient etc. Here, we will learn access modifiers.
Access
Modifier
1) private access modifier
□The private access modifier is accessible only within class.
□Example of private access modifier
✔ In this example, we have created two classes A and Simple. A
class contains private data member and private method. We
are accessing these private members from outside the
class, so there is compile time error.
class A{
private int data=40;
private void msg(){[Link]("Hello java");}
}
class A
{
private A()
{}//private constructor
void msg()
{
[Link]("Hello java");}
}
public class Simple
{
public static void main(String
args[]){ A obj=new A();//Compile
Time Error
}
}
Access
Modifier
2) default access modifier
* Ifyou don't use any modifier, it is treated as default bydefault.
The default modifier is accessible only within [Link] of
default access modifier
* In this example, we have created two packages pack and mypack.
We are accessing the A class from outside its package, since A
class is not public, so it cannot be accessed from outside the
package.
//save by //save by [Link]
[Link] package
package mypack;
pack; class A import pack.*;
{ class B{
void msg() public static
{[Link]("Hello
void
");}
main(String
}
args[])
{
In the above example, the scope A obj = new
of class A();//Compile
A and its methodTime
msg() is default so it cannot beError [Link]();//Compile
accessed from outside theTime
package. Error
Access
3) protected access
modifier
Modifer
* The protected access modifier is accessible within package and
outside the package but through inheritance only.
* The protected access modifier can be applied on the data member,
method and constructor. It can't be applied on the class.
* Example of protected access modifier
* In this example, we have created the two packages pack and
mypack. The A class of pack package is public, so can be accessed
from outside the package. But msg method of this package is
declared
be accessedas protected, so it
from outside thecan
//save by
cl/a/[Link] package
[Link] inheritance.
package mypack;
pack; public import pack.*;
class A
protected void msg() class B
{
{[Link]("Hello extends A{
");} public static
} void
main(String
args[])
{
Access
4) public access Modifier
modifier
* The public access modifier is accessible everywhere. It has
the widest scope among all other modifiers.
Example of public access modifier
//save by //save by
[Link] [Link]
package pack; package
public class A mypack;
{ import pack.*;
public void msg() class B{
{[Link]("Hello public static void main(String
");} args[])
} {
A obj = new
A();
[Link]();
Output:Hello }
}
Understanding all java access
modifiers
Access within class within package outside outside
Modifier package by package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Exception Handling in
□Java
The Exception Handling in Java is one of the powerful
mechanism to
handle the runtime errors so that normal flow of the application
can be maintained.
□ In this page, we will learn about Java exceptions, its
type and the difference between checked and unchecked
exceptions.
□ What is Exception in Java
□ Dictionary Meaning: 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.
□ What is Exception Handling
□ Exception Handling is a mechanism to handle runtime
errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc.
Exception
Advantage of Exception
Handling in
□ Java
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 use exception handling. Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception
occurs statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
□Suppose there are 10 statements in your program and there
occurs an exception at statement 5, the rest of the code will not
be executed i.e. statement 6 to 10 will not be executed. If we
perform exception handling, the rest of the statement will be
executed. That is why we use exception handling in Java.
Hierarchy of jav
exception a
classes
□
Types of Java
There are mainly two types of exceptions: checked and unchecked.
Exceptions
Here, an
error is considered as the unchecked exception. According to
Oracle, there are three types of exceptions:
✔ Checked Exception
✔ Unchecked Exception
✔ Error
□Difference between Checked and Unchecked Exceptions
1) Checked Exception
✔ The classes which directly inherit 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 which inherit RuntimeException are known as
unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but
they are checked at runtime.
Java Exception
Keyword Description
try Keywords
The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally.
It means, we can't use try block alone.
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 important code of the program.
It is executed whether an exception is handled or not.
OUTPUT :
OUTPUT :
Exception in thread "main"
[Link] at
[Link]([Link])
5. [Link] when getting length
of null array
OUTPUT :
OUTPUT :
main(String[] args)
{
synchronized(mutex)
{
[Link]("sync
hronized block");
}
}
NumberFormatExce
A Java NumberFormatException usually occurs when you try to do
ption
something like convert a String to a numeric value, like an int, float,
double, long, etc
NumberFormatException example
package [Link];
public class ConvertStringToNumber
{
public static void
main(String[] args)
{
try
{
// intentional error String s = "FOOBAR";
int i = [Link](s);
catch(NumberFormatException nfe)
{
[Link]();
}
}
}
Array IndexOutOfBound
Exception
•ArrayIndexOutOfBoundsException is thrown to
indicate that we are trying to access array element
with an illegal index.
•This exception is thrown when the index is either
negative or greater than or equal to the size of the
array.
ArrayIndexOutOfBounds Exception
Example
package
[Link];
import [Link];
public class
ArrayIndexOutOfBoundsExceptio
nExample
{
public static void
main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter size of int
array:"); int size = [Link]();
int[] intArray = new
int[size]; for (int i = 0; i <
size; i++)
{
[Link]("Please enter int value at index " +
i + ":"); intArray[i] = [Link]();
}
[Link]("Enter array index to get the
value:"); int index = [Link]();
[Link]();
OUTPUT :
•The catch block must be used after the try block only. You
can use multiple catch block with a single try block.
Problem without exception
handling
Let's try to understand the problem if we don't use a try-catch
block.
public class TryCatchExample1
{
public static void main(String[] args)
{
int data=50/0; //may throw
exception
[Link]("rest of the
code");
}
Output:
Output:
[Link]: / by zero rest of the code
Example
In this example, we also kept the code in a try block that will not
throw an exception.3
public class TryCatchExample3
{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
// if exception occurs,
//the remaining statement will not exceute
[Link]("rest of the
code");
}
Outpu
// handling the exception
t:
catch(ArithmeticException e) [Link]: / by
{ zero
[Link](e);
} }
}
catch multiple
□A exceptions
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.
□Points to remember
□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.
public class
{
E x a ple 1
MultipleCa
public statictch
void Blo ck
main(String[] args)
Output:
{
try{ Arithmetic Exception occurs
m 1 int a[]=new int[5]; rest of the code
a[5]=30/0;
}
catch(ArithmeticEx
ception e)
{[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Example 2
public class MultipleCatchBlock2 { Output:
public static void main(String[] args) { ArrayIndexOutOfBounds Exception occurs
try{ rest of the code
int a[]=new int[5];
[Link](a[10]);
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Example
3
In this example, try block contains two exceptions. But at a time
only one exception occurs and its corresponding catch block is
invoked.
public class MultipleCatchBlock3 catch(Exception e)
{ {
public static void main(String[] [Link]("Parent
args) { Exception o ccurs");
}
try{ [Link]("rest of the
int a[]=new code");
int[5]; }
a[5]=30/0; }
[Link]
ln(a[10]); Outpu
} t:
catch(ArithmeticExc Arithmetic Exception occurs rest of the
eption e) code
{
[Link]("Arithmetic
Excep tion occurs");
}
catch(ArrayIndexOutOfBoundsEx
ception e)
Java Nested try
□ The try block within a try block is known as nested try block in java.
block
Why use nested try block
□ Sometimes a situation may arise where a part of a block may cause one error
and the entire block itself may cause another error. In such cases, exception
handlers have to be nested.
Syntax:
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
class
Java nested try
try{ example
Excep6{
public static void main(String args[]){
try{
[Link]("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{[Link](e);}
try{
int a[]=new
int[5]; a[5]=4;
}
catch(ArrayIndexO
utOfBoundsExcepti
on e)
{ [Link](e);}
[Link]("other
statement);
}
catch(Exception e)
Java throw
exception
□ The Java throw keyword is used to explicitly throw an exception.
□ We can throw either checked or uncheked exception in java by
throw keyword. The throw keyword is mainly used to throw custom
exception. We will see custom exceptions later.
□ The syntax of java throw keyword is given below.
throw exception;
Output:
to the programmer that there may occur an exception so it is better for the
programmer to provide the exception handling code so that normal flow can be
maintained.
□ Exception Handling is mainly used to handle the checked exceptions. If there
occurs any unchecked exception such as NullPointerException, it is programmers
fault that he is not performing check up before the code being used.
example
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked
}exception
void n()throws
IOException{ m(); Output
} :
void p() exception handled
{ normal flow...
try
{
n()
;
}
catc
h(Exc
eptio
n e)
{Syst
em.o
[Link]
Throws
Example
□ There are two cases:
Case1:You caught the exception i.e. handle the exception using
try/catch.
Case2:You declare the exception i.e. specifying throws with the
method.
Case1: You handle the
In case you handle the exception, the code will be executed fine
exception
whether exception occurs during the program or not.
import [Link].*;
class M{
void method()throws IOException{
Output:exception handled
throw new IOException("device
error"); normal flow...
}
}
public class Testthrows2
{
public static void main(String
args[]){
try{
M m=new
M();
[Link]();
}
catch(Exception
e)
{
[Link]("exception
handled");}
Case2: You declare
A)In case you declare the exception, if exception does not occur,
the code
will
fine.
be executed
the
B)In case you declare the exception if exception excepti
occures, an
occur
import [Link].*;
class M{ Output: device operation
void method()throws IOException{ performed normal
[Link]("device flow...
operation per formed");
}
}
class Testthrows3{
public static void main(String
args[])thr ows IOException
{//declare
exception M
m=new M();
[Link]();
[Link]
("normal
imB ) P r o g ram if
po rt ja va .io. *;
exception occurs
class M{
void method()throws IOException{
throw new IOException("device
error");
}
}
class Testthrows4{
public static void main(String
args[])thro ws IOException
{ //declare
exception M
m=new M();
[Link]();
[Link]("
normal flow...");
}
}
Output:Runtime
Difference between throw and throws
in Java
No. throw throws
1) Java throw keyword is used to explicitly Java throws keyword is used to
throw an exception. declare an exception.
4) Throw is used within the method. Throws is used with the method
signature.
5) You cannot throw multiple exceptions. You can declare multiple
exceptions e.g.
public void method()throws
IOException,SQLException.
□ J aa vbloack thfatiins usaedltolyexecubte
Java finally block is
class TestFinallyBlock{
public static void main(String args[]){
Output:5
try{
int data=25/5;
finally block is always executed
[Link](dat
rest of the code...
a);
}
catch(NullPointerExce
ption e)
{[Link](e);}
{[Link]("finally block is
finallyex ecuted");}
always
[Link]("rest of the
code...");
}
}
Case 2: java finally example where exception occurs and not
handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
[Link](dat
a);
}
catch(NullPointerExce
ption e)
{[Link](e);}
finally
{[Link]("finally block is always
executed");} [Link]("rest of the
code...");
}
}
Output:
finally block is always executed Exception in thread main
[Link]:/ by zero
Case 3:java finally example where exception
occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
[Link](dat
a);
}
catch(ArithmeticExcep
tion e)
{[Link](e);
}
finally{[Link]("finally block is always
execu ted");}
[Link]("rest of the code...");
}
}
Output:
Exception in thread main [Link]:/ by zero
finally block is always executed
Multithread
□ Multithreading in java is a process of executing multiple threads
A thread is aing
simultaneously.
□ 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.
□ Advantages of Java Multithreading
I. 1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
II. 2) You can perform many operations together, so it saves time.
III. 3) Threads are independent, so it doesn't affect other threads if an exception
occurs in a single thread.
□ Multitasking is
Ma purocletssiotf
aexescuktinignmugltiple tasks simultaneously. We use multitasking
to utilize the CPU. Multitasking can be achieved in two ways:
1) Process-based Multitasking (Multiprocessing)
2) Thread-based Multitasking (Multithreading)
3) 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.
sub
Tprohcesrs,etheasmdallesit nunit ojf aprovceassing. 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.
□ Thread class:
Thread class provide constructors and methods to create and
perform operations on a [Link] class extends Object class
and implements Runnable interface.
□ Starting a
thread:
start() method of Thread class is used to start a newly
created thread. It performs following tasks:A new thread
starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run()
method will run.
1) Java Thread Example by extending
Thread class
class Multi extends Thread
{
public void run()
{
[Link]("thread is
running...");
}
public static void main(String
args[])
{
Multi t1=new
Multi(); [Link]();
}
}
Output: thread is
running...
2) Java Thread Example by
implementing Runnable
interface
class Multi3 implements Runnable
{
public void run()
{ [Link]("thread is
running...");
}