Nfs Notes PBLJ
Nfs Notes PBLJ
1|Page
NFS – NOTES FOR STUDY
Introduction to Java
Java is a high-level, robust, object-oriented, and secure programming language. It is both a
programming language and a platform.
• Developed By: Sun Microsystems (acquired by Oracle Corporation) in 1995.
• Father of Java: James Gosling.
• Initial Name: Originally called Oak. The name was changed to Java because "Oak"
was already registered.
Java provides a runtime environment (JRE) and APIs, which makes it a platform-
independent language.
2|Page
NFS – NOTES FOR STUDY
1. Simple
Java is designed to be simple and easy to learn:
• Syntax is clean and similar to C++, making it familiar to existing programmers.
• Complex features like explicit pointers and operator overloading are removed.
• Automatic Garbage Collection eliminates the need to remove unreferenced objects
manually.
2. Object-Oriented
Java follows the Object-Oriented Programming (OOP) paradigm, where everything is
treated as an object. This simplifies software development and maintenance.
Basic OOP Concepts:
• Object: Instance of a class containing data and behavior.
• Class: Blueprint for creating objects.
• Inheritance: Mechanism to reuse existing code.
• Polymorphism: Allows methods to perform different tasks based on the object.
• Abstraction: Hides implementation details.
• Encapsulation: Binds data and methods, restricting direct access to some elements.
3. Platform Independent
• Java is platform-independent due to its ability to compile code into bytecode.
• Bytecode is executed by the Java Virtual Machine (JVM) on any platform,
eliminating platform-specific dependencies.
4. Secured
• Java is known for its robust security features:
o No explicit pointers to prevent unauthorized memory access.
o Programs run inside a sandbox environment.
Key Security Features:
• Classloader: Separates local classes from imported ones for enhanced security.
• Bytecode Verifier: Ensures no illegal code violates object access rights.
• Security Manager: Controls access to resources like file systems or networks.
Additionally, developers can implement security protocols like SSL, JAAS, and
Cryptography.
3|Page
NFS – NOTES FOR STUDY
5. Robust
Java is designed to handle runtime errors and ensure reliability:
• Strong memory management system.
• No use of explicit pointers.
• Automatic Garbage Collection ensures efficient memory cleanup.
• Exception Handling and Type Checking mechanisms provide runtime stability.
6. Architecture Neutral
Java’s design ensures that its applications are independent of underlying hardware
architecture. For example:
• Primitive data types (e.g., int) have consistent sizes across platforms.
• Unlike C, where int size varies (2 bytes on 32-bit and 4 bytes on 64-bit systems),
Java allocates a fixed 4 bytes.
7. Portable
Java’s portability stems from its ability to execute bytecode on any platform with a
compatible JVM. Bytecode does not require any modifications for different platforms.
8. High Performance
• Java’s performance is better than traditional interpreted languages because
bytecode is close to native machine code.
• However, Java is slightly slower than compiled languages like C++ due to its
interpreted nature.
9. Distributed
• Java provides tools like Remote Method Invocation (RMI) and Enterprise JavaBeans
(EJB) to create distributed applications.
• Distributed computing enables files and applications to be accessed remotely.
10. Multithreaded
Java allows concurrent execution of multiple threads within the same program.
• Threads share a common memory area, reducing memory overhead.
• Useful in multimedia, web applications, and real-time systems.
11. Dynamic
Java supports dynamic class loading, meaning classes are loaded into the JVM as required.
• Supports functions from native languages like C and C++.
4|Page
NFS – NOTES FOR STUDY
C++ vs Java
Although Java and C++ share similarities, they differ significantly in many aspects:
5|Page
NFS – NOTES FOR STUDY
Java Packages
A package in Java is a collection of classes, interfaces, and sub-packages that help organize
and group related components. Java has two types of packages:
1. Built-in Packages: Predefined, such as java.util.* or java.io.*.
2. User-Defined Packages: Created by developers to group custom classes and
interfaces.
Advantages of Using Packages
• Reusability: Create reusable components.
• Better Organization: Efficiently manage hundreds of classes.
• Avoid Name Conflicts: Classes with the same name can exist in different packages.
Using Packages
1. Declare the package at the top of the program using package keyword.
2. Import the package using import keyword.
6|Page
NFS – NOTES FOR STUDY
Example:
// Calculator.java
package letmecalculate;
Sub-Packages
Packages can contain sub-packages to further organize classes. Example:
package letmecalculate.multiply;
7|Page
NFS – NOTES FOR STUDY
Access Modifiers
Java provides four access modifiers to control access levels:
Private Yes No No No
Examples:
1. Default: Accessible only within the package.
2. Private: Accessible only within the class.
3. Protected: Accessible within the package and subclasses.
4. Public: Accessible from anywhere.
Note: Go through the Code for all access modifiers
8|Page
NFS – NOTES FOR STUDY
9|Page
NFS – NOTES FOR STUDY
- **Nested Classes and Interfaces**: Classes and interfaces defined within another class.
10 | P a g e
NFS – NOTES FOR STUDY
**Key Points**:
- Static nested classes can only access static members of the outer class.
- Static nested classes improve modularity and encapsulation.
---
class InnerClass {
int y = 5;
11 | P a g e
NFS – NOTES FOR STUDY
**Output**: 15
void showInner() {
Inner inner = new Inner();
inner.display();
}
12 | P a g e
NFS – NOTES FOR STUDY
13 | P a g e
NFS – NOTES FOR STUDY
**Note**: Java does not support multiple inheritance with classes to avoid ambiguity
(diamond problem).
14 | P a g e
NFS – NOTES FOR STUDY
15 | P a g e
NFS – NOTES FOR STUDY
16 | P a g e
NFS – NOTES FOR STUDY
**Example of Encapsulation**:
```java
17 | P a g e
NFS – NOTES FOR STUDY
class Account {
private String name;
private double balance;
18 | P a g e
NFS – NOTES FOR STUDY
19 | P a g e
NFS – NOTES FOR STUDY
Exception Object
An exception object is an instance of an exception class created and handed to the Java runtime
when an exceptional event disrupts the normal flow of the application. This is called “to throw an
exception” because Java uses the throw keyword to hand the exception to the runtime. When a
method throws an exception object, the runtime searches the call stack for a corresponding
exception handler.
Exception Hierarchy
All exception classes in Java are subtypes of the java.lang.Exception class, which itself is a subclass of
the Throwable class. The Throwable class has two primary subclasses:
20 | P a g e
NFS – NOTES FOR STUDY
1. Error:
2. Exception:
Exceptions vs Errors
Definition Problems during program execution. Severe issues like system resource failure.
Handling Can be caught and handled in the program. Not typically handled by the program.
Java provides two different options to handle an exception. You can either use the try-catch-finally
approach to handle all kinds of exceptions. Or you can use the try-with-resource approach which
allows an easier cleanup process for resources.
Try-Catch-Finally:
That is the classical approach to handle an exception in Java. It can consist of 3 steps:
· a try block that encloses the code section which might throw an exception,
· a finally block which gets executed after the try block was successfully executed or a
thrown exception was handled.
The try block is required, and you can use it with or without a catch or finally block.
Let’s talk about the try block first. It encloses the part of your code that might throw the exception.
If your code throws more than one exception, you can choose if you want to:
· use a separate try block for each statement that could throw an exception or
· use one try block for multiple statements that might throw multiple exceptions.
The following example shows a try block which encloses three method calls.
21 | P a g e
NFS – NOTES FOR STUDY
try {
doSomething("A message");
doSomethingElse();
doEvenMore();
As you can see in the method definitions, only the first and the third method specify an exception.
The first one might throw a MyBusinessException, and the doEvenMore method might throw
a NumberFormatException.
In the next step, you can define one catch block for each exception class you want to handle and
one finally block. All checked exceptions that are not handled by any of the catch blocks need to be
specified.
You can implement the handling for one or more exception types within a catch block. As you can
see in the following code snippet, the catch clause gets the exception as a parameter. You can
reference it within the catch block by the parameter name.
22 | P a g e
NFS – NOTES FOR STUDY
try {
doSomething("A message");
doSomethingElse();
doEvenMore();
} catch (MyBusinessException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
The previous code sample shows two catch blocks. One to handle the MyBusinessException and
one to handle the NumberFormatException. Both blocks handle the exceptions in the same way.
Since Java 7, you can do the same with just one catch block.
try {
doSomething("A message");
doSomethingElse();
doEvenMore();
} catch (MyBusinessException|NumberFormatException e) {
e.printStackTrace();
The implementation of the catch blocks in the previous examples is very basic.
The printStackTrace method which writes the class, message and call stack of the exception to
system out.
at com.stackify.example.TestExceptionHandling.doSomething(TestExceptionHandling.java:84)
at
com.stackify.example.TestExceptionHandling.performBusinessOperation(TestExceptionHandling.ja
va:25)
In a real application, you might want to use a more advanced implementation. You can, for
example, show an error message to the user and request a different input or you could write a
record into the work log of your batch process. Sometimes, it might even be ok to catch and ignore
the exception.
23 | P a g e
NFS – NOTES FOR STUDY
The finally block gets executed after the successful execution of the try block or after one of
the catch blocks handled an exception. It is, therefore, a good place to implement any cleanup
logic, like closing a connection or an InputStream.
You can see an example of such a cleanup operation in the following code snippet.
The finally block will be executed, even if the instantiation of the FileInputStream throws
a FileNotFoundException or the processing of the file content throws any other exception.
try {
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
As you’ve seen, the finally block provides a good option to prevent any leaks. And before Java 7, it
was a best practice to put all cleanup code into a finally block.
24 | P a g e
NFS – NOTES FOR STUDY
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.
throw exception;
In this example, we have created the validate method that takes an integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
if(age<18)
else
System.out.println("welcome to vote");
validate(13);
The Java throws keyword is used to declare an exception. It gives an information 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 has not performed check up before the code being used.
25 | P a g e
NFS – NOTES FOR STUDY
//method code
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
m();
void p(){
try{
n();
obj.p();
System.out.println("normal flow...");
26 | P a g e
NFS – NOTES FOR STUDY
Exceptions Methods
Method Description
printStackTrace() Prints the stack trace of the exception to the standard error stream.
Types of Exceptions
1. Checked Exceptions:
2. Unchecked Exceptions:
Examples
Example of Error
recursiveMethod(10);
while (i != 0) {
i = i + 1;
recursiveMethod(i);
27 | P a g e
NFS – NOTES FOR STUDY
Output:
Example of Exception
int x = 100;
int y = 0;
Output:
java.lang.ArithmeticException: / by zero
1. Try-Catch-Finally
o Use a finally block for cleanup operations that must execute, regardless of an
exception.
Example:
try {
System.out.println(array[5]);
} catch (ArrayIndexOutOfBoundsException e) {
} finally {
System.out.println("Cleanup code.");
2. Throwing Exceptions
28 | P a g e
NFS – NOTES FOR STUDY
Example:
3. Throws Keyword
Example:
Common Exceptions
1. Checked Exceptions:
2. Unchecked Exceptions:
Custom Exceptions
Java allows developers to create their own exceptions by extending the Exception or
RuntimeException class.
Example:
super(message);
29 | P a g e
NFS – NOTES FOR STUDY
try {
validateAge(15);
} catch (InvalidAgeException e) {
Component Description
finally block Code that executes after try and catch, used for cleanup.
Unchecked exceptions in Java are subclasses of RuntimeException. They occur due to programming
errors, such as invalid arguments or logical issues. They are not checked at compile time, so the
programmer is not required to handle them explicitly.
30 | P a g e
NFS – NOTES FOR STUDY
1. ArithmeticException:
o Example:
2. ArrayIndexOutOfBoundsException:
o Example:
3. ArrayStoreException:
o Example:
4. ClassCastException:
o Example:
5. NullPointerException:
o Example:
6. NumberFormatException:
o Example:
7. IllegalArgumentException:
31 | P a g e
NFS – NOTES FOR STUDY
o Example:
8. IllegalStateException:
o Example:
9. StringIndexOutOfBoundsException:
o Example:
10. UnsupportedOperationException:
o Example:
Checked Exceptions
Checked exceptions are exceptions that must be either caught or declared in the method signature
using the throws keyword. They are checked at compile time.
1. SQLException:
o Example:
2. IOException:
o Example:
3. ClassNotFoundException:
32 | P a g e
NFS – NOTES FOR STUDY
o Example:
o Class.forName("com.unknown.Class");
4. InstantiationException:
o Example:
o clazz.newInstance();
5. NoSuchMethodException:
o Thrown when an attempt is made to access a method that does not exist.
o Example:
6. InterruptedException:
o Example:
Example:
super(message);
33 | P a g e
NFS – NOTES FOR STUDY
try {
validateAge(16);
} catch (InvalidAgeException e) {
Output:
1. Runtime Exceptions:
2. Checked Exceptions:
3. Custom Exceptions:
o Extend the Exception class for checked exceptions and RuntimeException for
unchecked exceptions.
4. Best Practices:
34 | P a g e
NFS – NOTES FOR STUDY
35 | P a g e