[go: up one dir, main page]

0% found this document useful (0 votes)
4 views11 pages

java programming notes4

Java packages are a way to group related classes and interfaces, helping to prevent naming conflicts and organize code. They can be built-in or user-defined, with access control managed through access modifiers like private, protected, and public. Exception handling in Java allows developers to manage runtime errors using try-catch blocks, while multithreading enables concurrent execution of tasks, improving application performance.

Uploaded by

diwakarkhushi69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

java programming notes4

Java packages are a way to group related classes and interfaces, helping to prevent naming conflicts and organize code. They can be built-in or user-defined, with access control managed through access modifiers like private, protected, and public. Exception handling in Java allows developers to manage runtime errors using try-catch blocks, while multithreading enables concurrent execution of tasks, improving application performance.

Uploaded by

diwakarkhushi69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Java Packages

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 {

public static void main(String[] args) {

System.out.println("This is my package!");

Save the file as MyPackageClass.java, and compile it:


C:\Users\Your Name>javac -d . MyPackageClass.java

This forces the compiler to create the "mypack" 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".

To run the MyPackageClass.java file, write the following:

C:\Users\Your Name>java mypack.MyPackageClass

The output will be:

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;

Access protection in packages


In Java, access protection in packages is managed through access modifiers, which control the visibility of
classes, methods, and variables across different packages. Java provides four levels of access control:
1. Private (private)
 Members declared private are accessible only within the same class.
 Not visible to other classes in the same package or different packages.
 Example:
class A {
private int data = 10;
private void display() {
System.out.println("Private method");
}
}

2. Default (Package-Private) (No Modifier)


 If no access modifier is specified, the member is accessible only within the same package.
class A {
int data = 10; // Default access
void display() { // Default access
System.out.println("Default method");
}
}

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;

System.out.println("Answer: " + ans);


}
}
Output:

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

Types of Java Exceptions


1. Checked Exceptions
Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-
time by the compiler. Examples of Checked Exception are listed below:
1. ClassNotFoundException: Throws when the program tries to load a class at runtime but the class is
not found because its not present in the correct location or it is missing from the project.
2. IOException: Throws when input/output operation fails
3. InstantiationException: Thrown when the program tries to create an object of a class but fails
because the class is abstract, an interface, or has no default constructor.
4. SQLException: Throws when there’s an error with the database.
5. FileNotFoundException: Thrown when the program tries to open a file that doesn’t exist

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

Unchecked exceptions are


Checked exceptions are checked at compile time.
Behaviour checked at run time.

Programming bugs like


External factors like file I/O and database connection
logical Errors cause the
cause the checked Exception.
Cause unchecked Exception.

The compiler ensures that you either handle the


The compiler does not
exception using a try-catch block or declare that your
require you to handle or
method throws the exception using
declare them.
Handling the throws keyword.
Requirement

Try, Catch, Throw, and Finally in Java


In Java, try, catch, throw, and finally are used for exception handling, allowing you to handle runtime errors
gracefully. Here's how each works:
1. try Block
The try block contains the code that may throw an exception. If an exception occurs, it is caught by the
corresponding catch block.
try {
int result = 10 / 0; // This will cause an ArithmeticException
}

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");
}

public static void main(String[] args) {


checkAge(16); // This will throw an exception
}
}
Output:
Exception in thread "main" java.lang.IllegalArgumentException: Age must be 18 or above

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.

Thread Life Cycle in Java (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

Explanation of Different Thread States


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.
o 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.
A program implementing multithreading acquires a fixed slice of time to each individual thread.
Each and every thread runs for a short span of time and when that allocated time slice is over, the
thread voluntarily gives up the CPU to the other thread, so that the other threads can also run for their
slice of time. Whenever such a scenario occurs, all those threads that are willing to run, waiting for
their turn to run, lie in the runnable state. In the runnable state, there is a queue where the threads lie.
o 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.
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.
For example, a thread (let's say its name is A) may want to print some data from the printer. However, at the
same time, the other thread (let's say its name is B) is using the printer to print some data. Therefore, thread
A has to wait for thread B to use the printer. Thus, thread A is in the blocked state. A thread in the blocked
state is unable to perform any execution and thus never consume any cycle of the Central Processing Unit
(CPU). Hence, we can say that thread A remains idle until the thread scheduler reactivates thread A, which is
in the waiting or blocked state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread scheduler to
determine which thread to choose and which one to reject, and the chosen thread is then given the
opportunity to run.
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:
o When a thread has finished its job, then it exists or terminates normally.
o 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.

You might also like