java programming notes4
java programming notes4
Packages in Java are a mechanism that encapsulates a group of classes, sub-packages, and interfaces.
Packages are used for:
Prevent naming conflicts by allowing classes with the same name to exist in different packages,
like college.staff.cse.Employee and college.staff.ee.Employee.
They make it easier to organize, locate, and use classes, interfaces, and other components.
Packages also provide controlled access for Protected members that are accessible within the same
package and by subclasses.
Also for default members (no access specifier) that are accessible only within the same package.
By grouping related classes into packages, Java promotes data encapsulation, making code reusable and
easier to manage. Simply import the desired class from a package to use it in your program.
Packages are divided into two categories:
Built-in Packages (packages from the Java API)
User-defined Packages (create your own packages)
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java Development
Environment.
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:
Example:
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 java.util.Scanner;
In the example above, java.util is a package, while Scanner is a class of the java.util package.
To import a whole package, end the sentence with an asterisk sign (*). The following example will
import ALL the classes in the java.util package:
import java.util.*;
User-defined Packages
To create your own package, you need to understand that Java uses a file system directory to store them. Just
like folders on your computer:
Example:
└── root
└── mypack
└── MyPackageClass.java
To create a package, use the package keyword:
MyPackageClass.java
package mypack;
class MyPackageClass {
System.out.println("This is my package!");
The -d keyword specifies the destination for where to save the class file. You can use any directory name,
like c:/user (windows), or, if you want to keep the package within the same directory, you can use the dot
sign ".", like in the example above.
Note: The package name should be written in lower case to avoid conflict with class names.
When we compiled the package in the example above, a new folder was created, called "mypack".
This is my package!
The package can be imported using the import keyword and the wild card (*). For example −
import mypack.*;
The class itself can be imported using the import keyword. For example −
import mypack.MyPackageClass;
3. Protected (protected)
Members declared protected are accessible within the same package and subclasses in different
packages.
If accessed from outside the package, it must be through inheritance.
Example:
package pack1;
public class A {
protected int data = 20;
protected void display() {
System.out.println("Protected method");
}
}
package pack2;
import pack1.A;
class B extends A {
void show() {
System.out.println(data); // Allowed because of inheritance
display();
}
}
4. Public (public)
public members are accessible from any package.
The class or member must be imported if accessed from another package.
Example:
package pack1;
public class A {
public int data = 30;
public void display() {
System.out.println("Public method");
}
}
package pack2;
import pack1.A;
class B {
public static void main(String[] args) {
A obj = new A();
System.out.println(obj.data); // Accessible
obj.display();
}
}
The effect of access specifiers for class, subclass, or package is enlisted below,
For example, if some variable is declared as protected, then the class itself can access it, its subclass can
access it and any class in the same package can also access it. Similarly, if the variable is declared as private
then that variable is accessible by that class only and its subclass can not access it.
Exception handling
Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms
like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc.
An Exception is an unwanted or unexpected event that occurs during the execution of a program (i.e.,
at runtime) and disrupts the normal flow of the program’s instructions. It occurs when something
unexpected things happen, like accessing an invalid index, dividing by zero, or trying to open a file that does
not exist.
Exception in Java is an error condition that occurs when something wrong happens during the program
execution.
Example: Showing an Arithmetic Exception or you can say divide by zero exception.
import java.io.*;
class Geeks {
public static void main(String[] args)
{
int n = 10;
int m = 0;
int ans = n / m;
Note: When an exception occurs and is not handled, the program terminates abruptly and the code after
it, will never execute.
Exceptions can occur due several reasons, such as:
Invalid user input
Device failure
Loss of network connection
Physical limitations (out-of-disk memory)
Code errors
Out of bound
Null reference
Type mismatch
Opening an unavailable file
Database errors
Arithmetic errors
2. Unchecked Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check these
exceptions at compile time. In simple words, if a program throws an unchecked exception, and even if we
didn’t handle or declare it, the program would not give a compilation error. Examples of Unchecked
Exception are listed below:
1. ArithmeticException: It is thrown when there’s an illegal math operation.
2. ClassCastException: It is thrown when you try to cast an object to a class it does not belongs to.
3. NullPointerException: It is thrown when you try to use a null object (e.g. accessing its methods or
fields)
4. ArrayIndexOutOfBoundsException: It occurs when we try to access an array element with an
invalid index.
5. ArrayStoreException: It happens when you store an object of the wrong type in an array.
Difference Between Checked and Unchecked Exceptions
Feature Checked Exception Unchecked Exception
2. catch Block
The catch block handles the exception thrown in the try block.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
}
Output:
Cannot divide by zero: / by zero
ArithmeticException : This is the type of exception being caught. It occurs when an arithmetic error
happens, such as division by zero.
e : This is the variable name that stores the exception object. It allows you to access details about the
exception, like its message and stack trace.
3. throw Statement
The throw statement in Java is used to explicitly throw an exception. It allows you to generate exceptions
manually instead of relying on Java to do it automatically.
public class ThrowExample {
static void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above");
}
System.out.println("Access granted");
}
4. finally Block
The finally block always executes, whether an exception occurs or not. It is typically used for resource
cleanup. A finally block is not mandatory but is often used in try-catch-finally structures.
public class FinallyExample {
public static void main(String[] args) {
try {
System.out.println("Inside try block");
} catch (Exception e) {
System.out.println("Inside catch block");
} finally {
System.out.println("Inside finally block");
}
}
}
Output:
Inside try block
Inside finally block
Multithreading in Java
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.
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.
4) Multithreading can significantly enhance the performance of applications by making better use of
multiple CPU cores. Each thread can run on a separate core, allowing for parallel processing and faster
execution of tasks.
5) In applications with a graphical user interface (GUI), multithreading can help keep the interface
responsive. Long-running tasks can be handled in the background by separate threads, preventing the main
thread from freezing and improving user experience.
6) Threads within the same process share the same memory and resources, which makes it easier to share
data between them without the need for complex inter-process communication mechanisms.
7) Using multiple threads can simplify the design of complex applications, allowing for more modular and
manageable code. For example, separate threads can be dedicated to different tasks, such as network
communication, file I/O, and computation.
8) Multithreading allows an application to continue processing while waiting for I/O operations to
complete. This leads to better utilization of CPU resources as threads can perform useful work during I/O
waits.