Java Packages Overview
Java Packages Overview
pdf
PDF
Package in Java
name collisions.
• Java provides a mechanism for partitioning the class
name space into more manageable Chunks
What is a Package?
package
• The package is both a naming and a visibility control
mechanism
In Java, a package is a namespace that groups related classes, interfaces, and sub-
packages together.
Common examples:
[Link] → input/output
[Link] → networking
Syntax
java
package package_name;
Copy code
Example
java
package mypack;
Copy code
📌 Rules
package statement must be the first line
bash
javac -d . [Link]
Copy code
This creates:
cpp
mypack/
└── [Link]
Copy code
How to Access a Package Class
There are three ways:
java
✔ No import needed
❌ Long and repetitive
java
import [Link];
class Test {
public static void main(String[] args) {
Hello obj = new Hello();
[Link]();
}
}
Copy code
java
import mypack.*;
class Test {
public static void main(String[] args) {
Hello obj = new Hello();
[Link]();
}
} Copy code
public ✔ ✔ ✔ ✔
protected ✔ ✔ ✔ ❌
default ✔ ✔ ❌ ❌
private ✔ ❌ ❌ ❌
File: [Link]
java
package college;
Copy code
File: [Link]
java
import [Link];
class Main {
public static void main(String[] args) {
Student s = new Student();
[Link]();
}
}
Copy code
If you want:
Short exam answer
Diagram of package structure
Viva questions on packages
Just tell me 👍
PACKAGE IN JAVA
1. WHAT IS A PACKAGE?
A package in Java is a namespace that groups related classes, interfaces, sub-packages,
Unique name had to be used for each class to avoid
👉 A package is a folder (directory) that contains related Java classes and interfaces.
mechanism
Formal Definition
Characteristics
Already available in Java
Contain ready-made classes and interfaces
Reduce development effort
Imported using import keyword
[Link] Networking
java
import [Link];
class Test {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int x = [Link]();
[Link](x);
}
}
Copy code
Characteristics
Created using package keyword
Used for large projects
Improves code structure
Helps in team-based development
Syntax
java
package package_name;
Copy code
Example
java
package mypack;
Copy code
bash
javac -d . [Link]
Copy code
cpp
mypack/ Copy code
└── [Link]
Example
java
class Test {
public static void main(String[] args) {
[Link] obj = new [Link]();
[Link]();
}
}
Copy code
Advantages
No import statement required
Disadvantages
Lengthy and repetitive
Reduces readability
Syntax
java
import package_name.ClassName;
Copy code
Example
java
import [Link];
class Test {
public static void main(String[] args) {
Hello obj = new Hello();
[Link]();
}
}
Copy code
✔ Most commonly used
✔ Cleaner code
Syntax
java
import package_name.*;
Copy code
Example
java
import mypack.*;
class Test {
public static void main(String[] args) {
Hello obj = new Hello();
[Link]();
}
}
Copy code
📌 * imports all classes of the package (not sub-packages).
public ✔ ✔ ✔ ✔
protected ✔ ✔ ✔ ❌
default ✔ ✔ ❌ ❌
private ✔ ❌ ❌ ❌
📌 Exam Highlight
👉 protected allows access in subclasses outside the package.
File 1: [Link]
java
package college;
Copy code
File 2: [Link]
java
import [Link];
class Main {
public static void main(String[] args) {
Student s = new Student();
[Link]();
}
Copy code
}
8. ADVANTAGES OF PACKAGES
Major Advantages
1. Code Organization
Logical grouping of related classes
2. Avoids Naming Conflicts
Same class names allowed in different packages
3. Reusability
Packages can be reused across projects
4. Security
Access control using access modifiers
5. Maintenance
Easier debugging and updates
6. Modularity
Large applications divided into modules
7. Team Development
Different teams work on different packages
8. Scalability
Easy to expand large systems
9. USES OF PACKAGES
Packages are used in:
1. Large software applications
2. Enterprise applications
3. Library creation
4. Framework development
5. API design
6. Distributed systems
7. Object-oriented project structuring
10. IMPORTANT EXAM POINTS (VERY IMPORTANT)
package must be first statement
Just tell me 🔥
INTERFACE IN JAVA
1. WHAT IS AN INTERFACE?
An interface in Java is a blueprint of a class that contains abstract methods, constants,
and (from Java 8 onwards) default and static methods.
👉 In simple words:
An interface specifies WHAT a class must do, but not HOW it does it.
Main Characteristics
1. An interface cannot be instantiated
2. Interface methods are:
public and abstract by default
Exam Highlight
📌 Java allows multiple inheritance through interfaces, but not through classes.
4. SYNTAX OF INTERFACE
Defining an Interface
java
interface InterfaceName {
// constants
// abstract methods
}
Copy code
Implementing an Interface
java
Interface Definition
java
interface Animal {
void sound(); // abstract method
Copy code
}
java
Copy code
Main Class
java
class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}
Copy code
Output
nginx
Dog barks
Copy code
interface Vehicle {
int speed = 80; // public static final by default
void run(); Copy code
}
java
Copy code
📌 Interface variables cannot be modified.
Interface 1
java
interface A {
void show();
}
Copy code
Interface 2
java
interface B {
void display();
}
Copy code
java
📌 Exam Point
✔ Java allows multiple inheritance using interfaces
❌ Java does NOT allow multiple inheritance using classes
interface A {
void methodA();
}
interface B extends A {
void methodB();
}
Copy code
Default Method
java
interface Demo {
default void msg() {
[Link]("Default method");
}
}
Copy code
Static Method
java
interface Demo {
static void show() {
[Link]("Static method");
}
}
Copy code
📌 Default methods provide backward compatibility.
Constructors ❌ No ✔ Yes
Instantiation ❌ No ✔ Yes
Just tell me 🔥
EXCEPTION IN JAVA
1. WHAT IS AN EXCEPTION?
Definition
An exception in Java is an abnormal condition or runtime error that disrupts the normal
flow of program execution.
👉 In simple words:
1. Compile-time Errors
Syntax errors
Detected by compiler
Example: missing semicolon
3. Logical Errors
Program runs but gives wrong output
Throwable
|
|-- Error
|
|-- Exception
|
|-- RuntimeException
Copy code
4.1 Error
Serious problems
Cannot be handled
Example: StackOverflowError, OutOfMemoryError
4.2 Exception
Exceptions that can be handled using exception handling mechanism.
2. Unchecked Exceptions
Occur at runtime
Subclasses of RuntimeException
Example: ArithmeticException, NullPointerException
Syntax
java
try {
// code that may cause exception
}
catch(ExceptionType e) {
// exception handling code
}
Copy code
java
class Demo {
public static void main(String args[]) {
try {
int a = 10 / 0;
[Link](a);
}
catch (ArithmeticException e) {
[Link]("Division by zero error");
}
}
}
Copy code
Output
vbnet
java
class MultiCatch {
public static void main(String args[]) {
try {
int a = [Link];
int b = 42 / a;
int arr[] = {1};
arr[5] = 10;
}
catch (ArithmeticException e) {
[Link]("Divide by zero");
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index error");
}
}
}
Copy code
8. finally BLOCK
Purpose
Executes always
Used for cleanup operations
Syntax
java
finally {
// cleanup code
}
Copy code
Example
java
class FinallyDemo {
public static void main(String args[]) {
try {
int a = 10 / 2;
[Link](a);
}
finally {
[Link]("Finally block executed");
}
}
}
Copy code
9. throw KEYWORD
Used to explicitly throw an exception.
Syntax
java
java
class ThrowDemo {
static void check(int age) {
if(age < 18)
throw new ArithmeticException("Not eligible");
else
[Link]("Eligible");
}
Copy code
Example
java
class ThrowsDemo {
static void demo() throws InterruptedException {
[Link](1000);
}
Copy code
11. USER-DEFINED (CUSTOM) EXCEPTION
java
Copy code
java
class Test {
static void check(int x) throws MyException {
if(x > 100)
throw new MyException("Value too large");
}
Copy code
Just tell me 👍
1. try STATEMENT
Meaning
The try block is used to enclose the code that may generate an exception.
Syntax
java
try {
// risky code
}
Copy code
Example
java
class TryDemo {
public static void main(String args[]) {
try {
int a = 10 / 0; // exception occurs
[Link](a);
}
catch (ArithmeticException e) {
[Link]("Division by zero error");
}
}
}
Copy code
2. catch STATEMENT
Meaning
The catch block is used to handle the exception thrown by the try block.
Key Points
Each catch handles a specific type of exception
Multiple catch blocks are allowed
The first matching catch is executed
Exception object contains error details
Syntax
java
catch(ExceptionType e) {
// handling code
}
Copy code
Example
java
class CatchDemo {
public static void main(String args[]) {
try {
int x = 10 / 0;
}
catch (ArithmeticException e) {
[Link]("Error: " + e);
}
[Link]("Program continues normally");
}
}
Copy code
Output
vbnet
Example
java
class MultiCatchDemo {
public static void main(String args[]) {
try {
int a = [Link];
int b = 42 / a;
int arr[] = {1};
arr[10] = 5;
}
catch (ArithmeticException e) {
[Link]("Divide by zero");
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index error");
}
}
}
Copy code
4. throw STATEMENT
Meaning
The throw statement is used to explicitly generate an exception manually.
Key Points
Used to create custom or predefined exceptions
Control is transferred to nearest catch
Mostly used for validation checks
Syntax
java
Example
java
class ThrowDemo {
static void checkAge(int age) {
if (age < 18)
throw new ArithmeticException("Not eligible to vote");
else
[Link]("Eligible to vote");
}
Copy code
Output
pgsql
5. finally STATEMENT
Meaning
The finally block contains code that always executes, whether an exception occurs or
not.
Key Points
Executes after try and catch
Executes even if:
exception occurs
exception does not occur
return statement is present
Commonly used to:
close files
close database connections
release resources
Syntax
java
finally {
// cleanup code
}
Copy code
Example
java
class FinallyDemo {
public static void main(String args[]) {
try {
int a = 10 / 2;
[Link](a);
}
catch (ArithmeticException e) {
[Link]("Error occurred");
}
finally {
[Link]("Finally block executed");
}
}
}
Copy code
Output
powershell
5
Finally block executed
Copy code
class FullDemo {
public static void main(String args[]) {
try {
int a = 10 / 0;
}
catch (ArithmeticException e) {
[Link]("Exception caught");
}
finally {
[Link]("Cleanup code executed");
}
}
}
Copy code
Just tell me 👍
Throwable
|
|---- Error
|
|---- Exception
|
|---- RuntimeException Copy code
3.1 ERRORS
Definition
Errors represent serious problems that occur due to system failure and cannot be handled
by the program.
Characteristics
Caused by JVM or hardware
Not recoverable
Not handled using try–catch
Examples
StackOverflowError
OutOfMemoryError
VirtualMachineError
Definition
Checked exceptions are exceptions that are checked at compile time.
Characteristics
Must be handled using try–catch or throws
Occur due to external factors
Compiler forces handling
Examples
IOException
SQLException
ClassNotFoundException
FileNotFoundException
Definition
Unchecked exceptions occur at runtime and are not checked at compile time.
Characteristics
Subclasses of RuntimeException
Caused due to programming mistakes
Handling is optional but recommended
Examples
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
NumberFormatException
📌 Exam Highlight
Checked → Compile time
Unchecked → Runtime
1. ArithmeticException
Cause
Occurs when an illegal arithmetic operation is performed.
Common Reason
Division by zero
Example
java
class ArithmeticDemo {
public static void main(String args[]) {
int a = 10 / 0;
[Link](a);
}
}
Copy code
Output
pgsql
2. NullPointerException
Cause
Occurs when a null reference is used to access an object or method.
Example
java
class NullDemo {
public static void main(String args[]) {
String s = null;
[Link]([Link]());
}
}
Copy code
Output
[Link]
Copy code
3. ArrayIndexOutOfBoundsException
Cause
Occurs when an array is accessed using an invalid index.
Example
java
class ArrayDemo {
public static void main(String args[]) {
int arr[] = {10, 20, 30};
[Link](arr[5]);
}
}
Copy code
Output
makefile
[Link]: 5
Copy code
4. NumberFormatException
Cause
Occurs when a string is converted into a number, but the string is not numeric.
Example
java
class NumberDemo {
public static void main(String args[]) {
String s = "abc";
int x = [Link](s);
} Copy code
}
Output
lua
5. ClassNotFoundException
Cause
Occurs when JVM tries to load a class that does not exist.
Type
✔ Checked Exception
Example
java
class ClassDemo {
public static void main(String args[]) {
try {
[Link]("Test");
}
catch (ClassNotFoundException e) { Copy code
Just tell me 👍